I found the following program on cplusplus.com.
// set::insert
#include <iostream>
#include <set>
int main (){
std::set<int> myset;
std::set<int>::iterator it;
std::pair<std::set<int>::iterator, bool> ret;
// set some initial values:
for (int i = 1; i <= 5; i++) myset.insert(i*10); // set: 10 20 30 40 50
ret = myset.insert(20); // no new element inserted
if (ret.second == false) it = ret.first; // "it" now points to element 20
myset.insert (it, 25); // max efficiency inserting
myset.insert (it, 24); // max efficiency inserting
myset.insert (it, 26); // no max efficiency inserting
int myints[] = {5, 10, 15}; // 10 already in set, not inserted
myset.insert (myints, myints+3);
std::cout << "myset contains:";
for (it = myset.begin(); it != myset.end(); it++)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}
The output of this program is:
myset contains: 5 10 15 20 24 25 26 30 40 50
On 16th line, the comment says that the std::set<int>::iterator it
now points to the element 20, the second element in the set. But I don't seem to understand why it happen so or how the statement if (ret.second == false) it = ret.first;
actually works.
It would be really helpful if someone explains me how this code works. However, it may be kept in mind that I'm new to std::set
.