C++ STL 之 map

map 是“关键字——值”对的集合。即

map<index, value>

其中 index 和 value 可以是各种类型,如 int, char, string,甚至是 STL 容器对象。

map 中的元素默认按 index 的增序进行排序,故要求 index 能够进行排序,这也意味着 map 中不存在两个元素拥有相同的 index。

定义

map<string,int> map_1;

初始化

map<string, int> map_1 = { { "I", 1 }, { "you", 2 }, { "he", 3 } };

添加元素

map<string, int> map_1 = { { "I", 1 }, { "you", 2 }, { "he", 3 } };
map_1.insert({ "she", 3 });

map 还有一个默认的机制:当我们通过下标访问 map 对象中并不存在的一个 index 对应的 value 时,访问并不会出错,该 map 对象会自动添加一个元素,其 index 为想要访问的值,value 为 value 类型的默认值

map<string, int> map_1 = { { "I", 1 }, { "you", 2 }, { "he", 3 } };
cout << map_1["she"];//输出:0
map_1["it"]++;
cout << map_1["it"];//输出:1

删除元素

map.erase(index):删除以 index 为索引的元素

map<string, int> map_1 = { { "I", 1 }, { "you", 2 }, { "he", 3 } };
map_1.erase("I");//map_1 = { { "you", 2 }, { "he", 3 } };

map.erase(p):删除迭代器 p 指向的元素

map<string, int> map_1 = { { "I", 1 }, { "you", 2 }, { "he", 3 } };
map_1.erase(map_1.begin());//map_1 = { { "you", 2 }, { "he", 3 } };

map.erase(b, e):删除由迭代器 b 和迭代器 e 所指向的范围内的元素

map<string, int> map_1 = { { "I", 1 }, { "you", 2 }, { "he", 3 } };
map_1.erase(map_1.begin(), map_1.begin()+2);//map_1 = { { "he", 3 } };

修改元素

与传统的数组类似,map 可以修改指定 index 所对应的 value。

map<string, int> map_1 = { { "I", 1 }, { "you", 2 }, { "he", 3 } };
map_1["I"] = 2;//map_1 = { { "I", 2 }, { "you", 2 }, { "he", 3 } };

访问元素

1、使用下标访问

不同于传统的数组,map 对象能以任何可排序的类型作为 index,来访问某个 index 所对应的值。这也是 map 容器最大的用处。

map<string, int> map_1 = { { "I", 1 }, { "you", 2 }, { "he", 3 } };
cout << map_1["you"];//输出:2

若不想使用该特性,可使用 set.at(index) 来访问 map 对象中 index 对象的值,此时,当 map 对象中不存在该 index 时,会抛出一个 out_of_range 的异常。

map<string, int> map_1 = { { "I", 1 }, { "you", 2 }, { "he", 3 } };
cout << map_1.at("you");//输出:2
cout << map_1.at("she");//错误

如果既不想在访问的 index 不在 map 对象中时使用其自动添加的功能,又不想在 map 对象中不存在该 index 时产生一个异常,则可以使用 find(),此函数在 map 对象中不存在欲访问的 index 时会返回 map 对象的尾后迭代器。

map<string, int> map_1 = { { "I", 1 }, { "you", 2 }, { "he", 3 } };
auto it_1 = map_1.find("I");//it_1 = map_1.begin();
auto it_2 = map_1.find("she");//it_2 = map_1.end();

2、使用迭代器访问

使用迭代访问 map 对象中的元素需要注意的是,此时迭代解引用后得到的元素并不是 value,而是 pair<index, value>

map<string, int> map_1 = { { "I", 1 }, { "you", 2 }, { "he", 3 } };
auto it = map_1.begin() + 1;
cout << it->first;//输出:you
cout << it->second;//输出:2

遍历元素

1、使用迭代器进行遍历

map<string, int> map_1 = { { "I", 1 }, { "you", 2 }, { "he", 3 } };
for(auto it=map_1.begin(); it!=map_1.end(); map_1++)
    cout << it->second << " ";
//输出:1 2 3 

2、使用 C11 新特性进行遍历

map<string, int> map_1 = { { "I", 1 }, { "you", 2 }, { "he", 3 } };
for(auto p:map_1)
    cout << p.second << " ";
//输出:1 2 3 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章