关联容器
map,set
map
map是一种关联式容器包含 键/值 key/value 相当于python中的字典
不允许有重复的key
map 无重复,有序
Map是STL的一个关联容器,它提供一对一(其中第一个可以称为关键字,每个关键字只能在map中出现一次,第二个可能称为该关键字的值)的数据 处理能力,这里说下map内部数据的组织,map内部自建一颗红黑树(一 种非严格意义上的平衡二叉树),这颗树具有对数据自动排序的功能,所以在map内部所有的数据都是有序的,后边我们会见识到有序的好处。
1、map简介
map是一类关联式容器。它的特点是增加和删除节点对迭代器的影响很小,除了那个操作节点,对其他的节点都没有什么影响。
对于迭代器来说,可以修改实值,而不能修改key。
2、map的功能
自动建立Key - value的对应。key 和 value可以是任意你需要的类型。
根据key值快速查找记录,查找的复杂度基本是log(n) 如果有1000个记录,最多查找10次,1,000,000个记录,最多查找20次。
快速插入Key -Value 记录。
快速删除记录
根据Key 修改value记录。
遍历所有记录。
map的插入,有4种
map插入,删除
#include <iostream> #include <map> #include <string> using namespace std; void printMap(map<int ,string> &map1) { if (!map1.size()) { cout<< "map为空" << endl; } else { cout<< "迭代器遍历 map:\n"; for (map<int, string>::iterator it = map1.begin(); it != map1.end(); it++) { cout << "key = " << it->first << " values = " << it->second << endl; } } } void test11() { // 插入,四种常用的方法 // 方法一 map<int, string> map1; map1.insert(pair<int ,string>(1, "teacher2")); map1.insert(pair<int ,string>(2, "teacher2")); // 方法二 map1.insert(make_pair(3, "teacher3")); map1.insert(make_pair(4, "teacher4")); // 方法三 map1.insert(map<int, string>::value_type(5, "teacher5")); map1.insert(map<int, string>::value_type(6, "teacher6")); // 方法四 map1[7] = "teacher7"; map1[8] = "teacher8"; // 遍历 printMap(map1); // map1.erase(map1.begin(), map1.end()); 共有4中删除方法 // 删除 for (auto it = map1.begin(); it != map1.end(); it++) { map1.erase(it); } printMap(map1); /* void erase( iterator pos ); void erase( iterator start, iterator end ); size_type erase( const KEY_TYPE &key ); erase()函数删除在pos位置的元素,或者删除在start和end之间的元素,或者删除那些值为key的所有元素。 */ } int main() { test11(); return 0; }