c++ - 访问 map<int,string[4]> 中的元素

标签 c++ gcc stl dictionary std

我将如何访问以下 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/

相关文章:

c++ - C/C++ 服务器不发送最后几行文件

c - 错误的 gcc 生成的程序集顺序,导致性能下降

C++ 11 移动语义和 STL 容器

c++ - 为什么 std::set 遍历所有元素的速度较慢?

c++ - unicode 编码的 wchar_t 的大小

c++ - 导入的库函数可以在内存中移动吗

c++ - 线程安全游戏引擎 : Multi-Threading Best Practices?

Code::在 C 中使用 OpenCV "undefined reference to ` cvFree _'|"时 block 返回错误

c++ - 尽管文件指针正确,但 fclose() 期间出现段错误

c++ - 如何实现 set::find() 以仅匹配一对中的键?