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


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?

4/25/2014 6:54:18 AM

Accepted Answer

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;
12/23/2009 7:08:31 PM

Use iterators:

std::set<int> si;
/* ... */
for(std::set<int>::iterator it=si.begin(); it!=si.end(); ++it)
    std::cout << *it << std::endl;

Note that many references like MSDN and provides examples - one example. ;)

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow