Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the elements in a set in C++? [duplicate]

Tags:

c++

set

stdset

I am confused as to how to get the elements in the set. I think I have to use the iterator but how do I step through it?

like image 363
SuperString Avatar asked Dec 23 '09 19:12

SuperString


2 Answers

For C++11 and newer:

std::set<int> my_set;
for (auto item : my_set)
    std::cout << item << endl;
like image 87
tvorez Avatar answered Oct 26 '22 18:10

tvorez


Replace type with, for example, int.. And var with the name of the set

for (set<type>::iterator i = var.begin(); i != var.end(); i++) {
   type element = *i;
}

The best way though is to use boost::foreach. The code above would simply become:

BOOST_FOREACH(type element, var) {
   /* Here you can use var */
}

You can also do #define foreach BOOST_FOREACH so that you can do this:

foreach(type element, var) {
   /* Here you can use var */
}

For example:

foreach(int i, name_of_set) {
   cout << i;
}
like image 25
Thomas Bonini Avatar answered Oct 26 '22 18:10

Thomas Bonini