C++之STL-Map使用
Map是STL的一个关联容器,它提供一对一(其中第一个可以称为关键字,每个关键字只能在map中出现一次,第二个称为该关键字的值)的数据处理能力,由于这个特性,在我们处理一对一数据的时候,在编程上提供快速通道。这里说下map内部数据的组织,map内部自建一颗红黑树(一 种非严格意义上的平衡二叉树),这颗树具有对数据自动排序的功能,所以在map内部所有的数据都是有序的
map使用格式
typedef map<key_type,value_type> map_type ;
map_type map_variable;
需要先声明头文件
#include <map>
#include <iostream>
#include <map>
#include <vector>
#include <list>
#include <deque>
using namespace std;
int main() {
typedef map<int, string> map_other;
map_other map_obj;
map_obj.insert(map<int, string>::value_type(1, "liming"));
map_obj.insert(pair<int, string>(2, "niu"));
for (map<int, string>::iterator iterator1 = map_obj.begin(); iterator1 != map_obj.end();
++iterator1) {
cout << (*iterator1).first << ":" << (*iterator1).second << endl;
}
return 0;
}
输出:
1:liming
2:niu