STL_MAP 水深无声 2022-07-17 04:16 235阅读 0赞 // accessing mapped values #include <iostream> #include <map> #include <string> int main() { std::map<char, std::string> mymap; //operator[] 返回指向second的指向的东西 mymap['a'] = "an element"; mymap['b'] = "another element"; mymap['c'] = mymap['b']; std::cout << "mymap['a'] is " << mymap['a'] << '\n'; std::cout << "mymap['b'] is " << mymap['b'] << '\n'; std::cout << "mymap['c'] is " << mymap['c'] << '\n'; std::cout << "mymap['d'] is " << mymap['d'] << '\n'; std::cout << "mymap now contains " << mymap.size() << " elements.\n"; system("pause"); return 0; } // map::insert (C++98) #include <iostream> #include <map> int main() { std::map<char, int> mymap; mymap.insert(std::pair<char, int>('a', 100));//pair使两个值关联起来 mymap.insert(std::pair<char, int>('z', 200));//pair键值对 std::pair<std::map<char, int>::iterator, bool> ret; ret = mymap.insert(std::pair<char, int>('z', 500)); if (ret.second == false) { std::cout << "element 'z' already existed"; std::cout << " with a value of " << ret.first->second << '\n'; } // second insert function version (with hint position): std::map<char, int>::iterator it = mymap.begin(); mymap.insert(it, std::pair<char, int>('b', 300)); // max efficiency inserting mymap.insert(it, std::pair<char, int>('c', 400)); // no max efficiency inserting // third insert function version (range insertion): std::map<char, int> anothermap; anothermap.insert(mymap.begin(), mymap.find('c')); // showing contents: std::cout << "mymap contains:\n"; for (it = mymap.begin(); it != mymap.end(); ++it) std::cout << it->first << " => " << it->second << '\n'; std::cout << "anothermap contains:\n"; for (it = anothermap.begin(); it != anothermap.end(); ++it) std::cout << it->first << " => " << it->second << '\n'; system("pause"); return 0; } ERASE: // erasing from map #include <iostream> #include <map> int main() { std::map<char, int> mymap; std::map<char, int>::iterator it; // 插入数据 mymap['a'] = 10; mymap['b'] = 20; mymap['c'] = 30; mymap['d'] = 40; mymap['e'] = 50; mymap['f'] = 60; it = mymap.find('b'); mymap.erase(it);//找到b的迭代器删除 mymap.erase('c');//通过key值进行删除 it = mymap.find('e'); mymap.erase(it, mymap.end()); //删除e到结束的所有 //打印出所有的元素 for (it = mymap.begin(); it != mymap.end(); ++it) std::cout << it->first << " => " << it->second << '\n'; system("pause"); return 0; } // map::find #include <iostream> #include <map> int main() { std::map<char, int> mymap; std::map<char, int>::iterator it; mymap['a'] = 50; mymap['b'] = 100; mymap['c'] = 150; mymap['d'] = 200; it = mymap.find('b');//找到b的迭代器 if (it != mymap.end())//找到后 mymap.erase(it);//删除 std::cout << "elements in mymap:" << '\n'; std::cout << "a => " << mymap.find('a')->second << '\n'; std::cout << "c => " << mymap.find('c')->second << '\n'; std::cout << "d => " << mymap.find('d')->second << '\n'; system("pause"); return 0; }
相关 HDU - 2112-HDU Today 最段路径+STLmap HDU Today 经过锦囊相助,海东集团终于度过了危机,从此,HDU的发展就一直顺风顺水,到了2050年,集团已经相当规模了,据说进入 你的名字/ 2022年06月06日 00:58/ 0 赞/ 202 阅读
还没有评论,来说两句吧...