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?
For C++11 and newer:
std::set<int> my_set;
for (auto item : my_set)
std::cout << item << endl;
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With