×

# KJCP3 - Editorial

Take Turns

Author: Dipen Ved
Tester: Dipen Ved
Editorialist: Nirali

EASY

# PREREQUISITES:

Use of iterators and sets

# PROBLEM:

Given two lists, you have to sort them and print them alternatively starting with list one.

# QUICK EXPLANATION:

The input is taken using two 'sets' and two 'for loops' for two lists. Take two iterators, each pointing to the beginning of the respective sets. Using a for loop, alternatively print the numbers the two iterators are pointing to.

# EXPLANATION:

Let's first consider solving the problem for a single test case. We are given two lists. We have to take the input using set so that they are already sorted and we don't have to write a separate code again for sorting the list. So, using for loop and insert function -

for(int i=0;i<n;i++) {
int temp;
scanf("%d",&temp);
set1.insert(temp);
}


Here, n is the size of the list and temp is the number in the list Similarly, for the second list. Now, we wish to print the elements of the lists alternatively starting with list one. So let's put an iterator to point to the beginning to set2.

set<int>::iterator it2 = set2.begin();


We also want an iterator pointing to the start of set1, which we will do in the for loop.

for(set <int>::iterator it1 = set1.begin();it1!=set1.end() && it2!=set2.end();it1++,it2++) {
cout<<*it1<<" "<<*it2<<" ";
}


The for loop will run till both the iterators reach the end of their respective sets and alternatively both sets will be printed.

# AUTHOR'S AND TESTER'S SOLUTIONS:

Solution can be found here

4★vedipen
824
accept rate: 25%

19.8k350498541

 toggle preview community wiki:
Preview

By Email:

Markdown Basics

• *italic* or _italic_
• **bold** or __bold__
• image?![alt text](/path/img.jpg "title")
• numbered list: 1. Foo 2. Bar
• to add a line break simply add two spaces to where you would like the new line to be.
• basic HTML tags are also supported
• mathemetical formulas in Latex between \$ symbol

Question tags:

×278
×160
×61
×25
×9
×1

question asked: 11 Nov '16, 18:08

question was seen: 430 times

last updated: 07 Jun '17, 17:00