STL - 容器 - Map(一)
MapTest.cpp
#include <map> #include <string> #include <iostream> #include <algorithm> #include "MapTest.h" using namespace std; void MapTest::simpleEnumeration() { map<string,double> coll { { "tim", 9.9 }, { "struppi", 11.77 } } ; // for range-based enumeration cout << "for range-based enumeration: " << endl; for (auto elem : coll) { cout << elem.first << ": " << elem.second << endl; } // iterating cout << "iterating: " << endl; map<string, double>::iterator pos; for (pos = coll.begin(); pos != coll.end(); ++pos) { cout << pos->first << ": " << pos->second << endl; } // square the value of each element: for_each (coll.begin(), coll.end(), [] (pair<const string,double>& elem) { elem.second *= elem.second; }); // print each element: cout << "for_each lambda enumeration: " << endl; for_each (coll.begin(), coll.end(), [] (const map<string,double>::value_type& elem) { cout << elem.first << ": " << elem.second << endl; }); } void MapTest::run() { printStart("simpleEnumeration()"); simpleEnumeration(); printEnd("simpleEnumeration()"); }
运行结果:
--------------- simpleEnumeration(): Run Start ----------------
for range-based enumeration:
truppi: 11.77
im: 9.9
terating:
truppi: 11.77
im: 9.9
or_each lambda enumeration:
truppi: 138.533
im: 98.01
--------------- simpleEnumeration(): Run End ----------------
技术改变世界