How to get the elements in a set in C++?

SuperString picture SuperString · Dec 23, 2009 · Viewed 63.7k times · Source

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?

Answer

Thomas Bonini picture Thomas Bonini · Dec 23, 2009

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;
}