C++ STL map获取键对应值的几种方法(超详细)
庆幸的是,map 容器的类模板中提供了以下 2 种方法,可直接获取 map 容器指定键对应的值。注意,使用 map 容器存储的各个键值对,其键的值都是的,因此指定键对应的值最多有 1 个。
1) map 类模板中对
[ ]
运算符进行了重载,这意味着,类似于借助数组下标可以直接访问数组中元素,通过指定的键,我们可以轻松获取 map 容器中该键对应的值。举个例子:
#include <iostream>
#include <map> // map
#include <string> // string
using namespace std;
int main() {
//创建并初始化 map 容器
std::map<std::string, std::string>myMap{ {"STL教程","http://c.biancheng网站站点" rel="nofollow" />
http://c.biancheng网站站点" rel="nofollow" />
#include <iostream>
#include <map> // map
#include <string> // string
using namespace std;
int main() {
//创建空 map 容器
std::map<std::string, int>myMap;
int cValue = myMap["C语言教程"];
for (auto i = myMap.begin(); i != myMap.end(); ++i) {
cout << i->first << " "<< i->second << endl;
}
return 0;
}
程序执行结果为:
C语言教程 0
显然,对于空的 myMap 容器来说,其内部没有以 "C语言教程" 为键的键值对,这种情况下如果使用 [ ] 运算符获取该键对应的值,其功能就转变成了向该 myMap 容器中添加一个<"C语言教程",0>
键值对(由于 myMap 容器规定各个键值对的值的类型为 int,该类型的默认值为 0)。实际上,[ ] 运算符确实有“为 map 容器添加新键值对”的功能,但前提是要保证新添加键值对的键和当前 map 容器中已存储的键值对的键都不一样。例如:
#include <iostream>
#include <map> // map
#include <string> // string
using namespace std;
int main() {
//创建空 map 容器
std::map<string, string>myMap;
myMap["STL教程"]="http://c.biancheng网站站点" rel="nofollow" />
Python教程 http://c.biancheng网站站点" rel="nofollow" /> #include <iostream>
#include <map> // map
#include <string> // string
using namespace std;
int main() {
//创建并初始化 map 容器
std::map<std::string, std::string>myMap{ {"STL教程","http://c.biancheng网站站点" rel="nofollow" />
http://c.biancheng网站站点" rel="nofollow" />
#include <iostream>
#include <map> // map
#include <string> // string
using namespace std;
int main() {
//创建并初始化 map 容器
std::map<std::string, std::string>myMap{ {"STL教程","http://c.biancheng网站站点" rel="nofollow" />
C语言教程 http://c.biancheng网站站点" rel="nofollow" />
#include <iostream>
#include <map> // map
#include <string> // string
using namespace std;
int main() {
//创建并初始化 map 容器
std::map<std::string, std::string>myMap{ {"STL教程","http://c.biancheng网站站点" rel="nofollow" />
C语言教程 http://c.biancheng网站站点" rel="nofollow" />