How to: Iterate Over STL Collection with for each
In addition to .NET Framework collections, the for each keyword can also be used to iterate over Standard C++ Library (STL) collections. An STL collection is also known as a container. For more information, see STL Containers.
This sample uses for each in a <map>.
// for_each_stl.cpp
// compile with: /EHsc
#include <map>
#include <iostream>
#include <string>
using namespace std;
int main() {
int retval = 0;
map<string, int> months;
months["january"] = 31;
months["february"] = 28;
months["march"] = 31;
months["april"] = 30;
months["may"] = 31;
months["june"] = 30;
months["july"] = 31;
months["august"] = 31;
months["september"] = 30;
months["october"] = 31;
months["november"] = 30;
months["december"] = 31;
map<string, int> months_30;
for each( pair<string, int> c in months )
if ( c.second == 30 )
months_30[c.first] = c.second;
for each( pair<string, int> c in months_30 )
retval++;
cout << "Months with 30 days = " << retval << endl;
}
This sample uses const& for an iteration variable with STL containers. You can use an & as an iteration variable on any collection of a type that can be declared as a T&.
// for_each_stl_2.cpp
// compile with: /EHsc
#include <vector>
#include <iostream>
using namespace std;
int main() {
int retval = 0;
vector<int> col(3);
col[0] = 10;
col[1] = 20;
col[2] = 30;
for each( const int& c in col )
retval += c;
cout << "retval: " << retval << endl;
}
A Note on enumerating over a std::map and stdext::hash_map.
When enumerating over a map, both ordered and unordered(hash_map), the type for the loop identifier must be std::pair<const KeyType, ValueType> if you wish to get a const reference to the current element. This is especially true when the value type is another container or class type. When getting a temperary copy, any compatible std::pair will work otherwise.
Example:
for (int i = 0; i != 5; ++i)
for (int c = 0; c != 5; ++c)
mv[i].push_back(c);
for each (const std::pair<const int, std::vector<int>> & p in mv)
for each (int i in p.second)
std::cout << "mv[" << p.first << "][" << i <<"] = " << i << std::endl;
- 10/17/2008
- 6XGate