2014年01月23日 星期四 16:24
map是C++ STL Container中重要的一员,内部实现一般是平衡二叉树,用途非常广泛,编程示例如下:
#include <iostream> #include <string> #include <map> using namespace std; template<class T> void print_elements(T &elem){ for(auto &p : elem) { cout << p.first << " : " << p.second << endl; } } int main(int argc, char **argv) { map<string,string> m1; m1["mengguang"]="mengguang@gmail.com"; print_elements(m1); cout << "is m1 empty? " << m1.empty() << endl; cout << "size of m1: " << m1.size() << endl; cout << "finding mengguang..." << endl; auto p=m1.find("mengguang"); if( p != m1.end()) { cout << "got " << p->second << endl; } else { cout << "not found." << endl; } m1.insert(make_pair("mengkang","mengkang@163.com")); m1.insert({"menghui","menghui@sina.com"}); m1.erase("mengguang"); print_elements(m1); m1.clear(); cout << "is m1 empty? " << m1.empty() << endl; cout << "size of m1: " << m1.size() << endl; cout << m1["non_exists"] << endl; print_elements(m1); return 0; }
参考资料:
Zeuux © 2024
京ICP备05028076号