14

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?

hivert
  • 10,579
  • 3
  • 31
  • 56
SuperString
  • 21,593
  • 37
  • 91
  • 122
  • Both answers below are correct, but to be a bit more direct: Iterators are moved forward or backward through the result set using the increment (++) and decrement (--) operators. – Toji Dec 23 '09 at 19:12

6 Answers6

20

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;
}
Andreas Bonini
  • 44,018
  • 30
  • 122
  • 156
7

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 cplusplus.com provides examples - one example. ;)

theharshest
  • 7,767
  • 11
  • 41
  • 51
Georg Fritzsche
  • 97,545
  • 26
  • 194
  • 236
5

For C++11 and newer:

std::set<int> my_set;
for (auto item : my_set)
    std::cout << item << endl;
tvorez
  • 421
  • 5
  • 6
4

To list all the elements in the set you can do something like:

#include <iostream>
#include <set>
using namespace std;

int main ()
{
  int myints[] = {1,2,3,4,5};
  set<int> myset (myints,myints+5);

  set<int>::iterator it;

  cout << "myset contains:";
  for ( it=myset.begin() ; it != myset.end(); it++ )
    cout << " " << *it;

  cout << endl;

  return 0;
}

To check if a specific elements in the set or not you can use the find() method from the set STL class

codaddict
  • 445,704
  • 82
  • 492
  • 529
3

I'm liking what I'm seeing in VS2010 Beta2 using C++0x lambda syntax:

std::for_each( s.begin(), s.end(), 
               [](int value)
               { 
                  // what would be in a function operator() goes here.
                  std::cout << value << std::endl; 
               } );
oz10
  • 153,307
  • 27
  • 93
  • 128
1
set<int> os;
for (auto itr  = os.begin(); itr != os.end() ; ++itr) cout << *itr << endl;
skpro19
  • 519
  • 7
  • 10