我将如何访问以下 map 中的元素:
map<int, string[4]> * my_map;
我以前是通过 at() 运算符来完成的
string * val_ptr = my_map->at(key);
最近,我发现这是我的编译器的一个非标准特性,正确的方法是通过 operator[]
。不幸的是,编译器一直试图将我的 key 转换为 string [4]
:
string * val_ptr = my_map->operator[](key);
error: conversion from ‘int’ to non-scalar type ‘std::string [4]’ requested
我在网上看过,但似乎没有任何带有字符串数组映射的示例。我在做无效的事情吗?我应该改用 vector 吗?如果是这样,创建和访问速度会慢吗?
最佳答案
.at()
函数的使用不再是非标准的。它在标准 C+11 中(参见 doc )。
现在,这个,
string * val_ptr = my_map->operator[](key);
这是正确的,但应该写成:
string * val_ptr = (*my_map)[key];
因为它更简洁。
至于编译错误,在别的地方。
事实上,我认为问题出在某个地方,是由 map 的指针声明引起的。为什么不将 map 声明为:
map<int, string[4]> my_map; //no pointer
然后使用
string * val_ptr = my_map[key];
如果你使用 std::vector
会更好:
std::map<int, std::vector<std::string> > my_map; //no pointer
然后使用
std::vector<std::string> & val = my_map[key];
关于c++ - 访问 map<int,string[4]> 中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8464787/