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?
+3
A:
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. ;)
Georg Fritzsche
2009-12-23 19:07:44
+4
A:
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
2009-12-23 19:08:31
+1
A:
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
2009-12-23 19:12:06
A:
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;
} );
ceretullis
2009-12-24 06:31:36