C++ std::map 取值方式
C++ std::map 取值方式
文章目录
- C++ std::map 取值方式
- 1、常用取值方式
- 2、遍历的方式取值
- 3、.at()的方式取值
- 4、数组下标[]的方式取值
- 5、数组下标[]的方式取值的注意事项
- 5.1 使用[] 取值,如果不存在,不会报错,但会打印空,并且会自动插入一条 该键值的数据
- 5.2 C++ map容器在const修饰下将无法使用“[]“来获取键值
1、常用取值方式
-
方式1:遍历的方式取值
-
方式2:.at()的方式取值
-
方式3: 数组下标[] 的方式取值
2、遍历的方式取值
详见 C++ std::map几种遍历方式(正序、倒序) https://aduandniuniu.blog.csdn.net/article/details/136031020?spm=1001.2014.3001.5502
3、.at()的方式取值
#include <iostream>
#include <map>
int main()
{
std::map<std::uint32_t, std::string> myMap = {{1, "one"}, {2, "two"}, {3, "three"}};
// 使用迭代器倒序遍历map
std::map<std::uint32_t, std::string>::iterator iter;
for (iter = myMap.begin(); iter != myMap.end(); ++iter)
{
std::cout << iter->first << " => " << iter->second << '\n';
}
std::cout << " Key = 1, => Value = " << myMap.at(1) << '\n';
std::cout << " Key = 1, => Value = " << myMap.at(2) << '\n';
std::cout << " Key = 1, => Value = " << myMap.at(3) << '\n';
return 0;
}
4、数组下标[]的方式取值
#include <iostream>
#include <map>
int main()
{
std::map<std::uint32_t, std::string> myMap = {{1, "one"}, {2, "two"}, {3, "three"}};
// 使用迭代器倒序遍历map
std::map<std::uint32_t, std::string>::iterator iter;
for (iter = myMap.begin(); iter != myMap.end(); ++iter)
{
std::cout << iter->first << " => " << iter->second << '\n';
}
std::cout << " Key = 1, => Value = " << myMap[1] << '\n';
std::cout << " Key = 1, => Value = " << myMap[2] << '\n';
std::cout << " Key = 1, => Value = " << myMap[3] << '\n';
return 0;
}
5、数组下标[]的方式取值的注意事项
-
使用[] 取值,如果不存在,不会报错,但会打印空,并且会自动插入一条 该键值的数据
-
C++ map容器在const修饰下将无法使用“[]“来获取键值
5.1 使用[] 取值,如果不存在,不会报错,但会打印空,并且会自动插入一条 该键值的数据
#include <iostream>
#include <map>
int main()
{
std::map<std::uint32_t, std::string> myMap = {{1, "one"}, {2, "two"}, {3, "three"}};
// 使用迭代器倒序遍历map
std::map<std::uint32_t, std::string>::iterator iter;
for (iter = myMap.begin(); iter != myMap.end(); ++iter)
{
std::cout << iter->first << " => " << iter->second << '\n';
}
std::cout << " Key = 1, => Value = " << myMap[1] << '\n';
std::cout << " Key = 1, => Value = " << myMap[2] << '\n';
std::cout << " Key = 1, => Value = " << myMap[3] << '\n';
//不会报错,但自动插入一条key值为4的值,此时 myMap 数据条数增加了
std::cout << " Key = 1, => Value = " << myMap[4] << '\n';
// 使用迭代器倒序遍历map
std::map<std::uint32_t, std::string>::iterator iter;
for (iter = myMap.begin(); iter != myMap.end(); ++iter)
{
std::cout << iter->first << " => " << iter->second << '\n';
}
return 0;
}
5.2 C++ map容器在const修饰下将无法使用“[]“来获取键值
#include <iostream>
#include <map>
int main()
{
const std::map<std::uint32_t, std::string> myMap = {{1, "one"}, {2, "two"}, {3, "three"}};
// const 就不能使用[]获取结果,
std::cout << " Key = 1, => Value = " << myMap[1] << '\n'; // const 就不能使用[]获取结果
std::cout << " Key = 1, => Value = " << myMap[2] << '\n';
std::cout << " Key = 1, => Value = " << myMap[3] << '\n';
return 0;
}
对于const的对象使用了非const的成员函数:std::map::[]本身不是const成员函数(操作符),对于不在map中的关键字,使用下标操作符会创建新的条目,改变了map。
解决方法是使用at成员函数: myMap.at(3); // 可以使用at成员方法来解决