#include <iostream> #include <string> #include <iomanip> #include <map> template<typename Map> void print_map(Map& m) { std::cout << '{'; for(auto& p : m) std::cout << p.first << ":" << p.second << ' '; std::cout << '}'<<std::endl; } struct Point { double x, y; }; struct PointCmp { bool operator()(const Point& lhs, const Point& rhs) const { return lhs.x < rhs.x; } }; int main() { using namespace std; //freopen("d://1.text", "r", stdin); //default constructor std::map<std::string, int> map1; map1["something"] = 69; map1["anything"] = 199; map1["that thing"] = 50; std::cout << "map1= "; print_map(map1); //range constructor //从anything到结尾 map<string, int> iter(map1.find("anything"), map1.end()); cout << " iter= "; print_map(iter); cout << "map1= "; print_map(map1); //copy construct map<string, int> copied(map1); cout << " copied= "; print_map(copied); cout << "map1 = "; print_map(map1); //move construct map<string, int> moved(std::move(map1)); cout<<endl<<"moved = "; print_map(moved); cout<<"map1 = ";print_map(map1); //initalizer list constructor const map<string,int> init{ {"this",100}, {"can",100}, {"be",100}, {"const",100}, }; cout<<" init = ";print_map(init); //custom key class option 1; //use a comparison struct map<Point,double,PointCmp>mag = { {{5,-12},13}, {{3,4},5}, {{8,-15},17} }; for(auto p:mag) cout<<"The magnitude of("<<p.first.x <<", "<<p.first.y<<") is " <<p.second<<endl; //Custom Key class option 2: //use a comparison lambda //This lambda sorts points according to their magnitudes, where note that // these magnitudes are taken from the local variable mag //声明一个比较器 auto cmplambda = [&mag](const Point &lhs,const Point& rhs){return mag[lhs] < mag[rhs];}; //you could also use a lambda that is not dependent on local variables,like this: //auto cmpLambda= [](const Point& lhs,const Point& rhs){return lhs.y < rhs.y;}; map<Point,double,decltype(cmplambda)>magy(cmplambda); //various ways of inserting elements: magy.insert(pair<Point,double>({5,-12},13)); magy.insert({{3,4},5}); magy.insert({Point{-8.0,-15.0},17}); cout<<" "; for(auto p :magy) { cout<<"The magnitude of {"<<p.first.x <<". "<<p.first.y<<") is " <<p.second<<" "; } map<Point,double>::iterator it; //use iterator cout<<' '; for(it=magy.begin();it!=magy.end();it++) { cout<<"The magnitude of {"<<it->first.x <<". "<<it->first.y<<") is " <<it->second<<" "; } return 0; }
原文地址:https://en.cppreference.com/w/cpp/container/map/map