如何使用字符串指针访问映射的键
How to access keys of maps using a string pointer
我正在尝试使用字符串*指针而不是其实际值来访问地图。 每当我使用此指针时,maps 键都会返回错误的值。
mymap_comp_for_c.insert(pair<string, unsigned short int>("M", 0b1110000));
_c_parts[1]
保存 M 的值
但 value+= mymap_comp_for_c[c_parts[1]]
返回分配给"M">
像"M"这样的指针以后不会匹配另一个指针"M"或&string("M"(。它是相同的类型(const char*(,但值不同,您将不同的指针值用作键。
map<string*,int> x;
x["m"] = 5;
int y = x["m"]; // y not necessarily 5.
第 3 行中的"m">和上一行中的"m"具有不同的指针值。编译器可能会使用字符串池进行优化,让您相信它有效,但实际上这是一个很难找到的错误。
如果c_parts
确实是一个std::string*
数组,则需要先用*c_parts[index]
取消引用其中的指针,然后才能使用它从地图中提取数据。例:
#include <iostream>
#include <map>
#include <array>
int main() {
std::map<std::string, int> mymap_comp_for_c;
mymap_comp_for_c.emplace("M", 0b1110000); // emplace: easier than creating the pair manually
// an array of std::string*
std::string M = "M";
std::array<std::string*, 2> c_parts = {nullptr, &M};
for(auto& strptr : c_parts) {
if(strptr) { // check that it's not a nullptr
// dereference the std::string* and print the value in the map
std::cout << std::hex << mymap_comp_for_c[*strptr] << "n";
}
}
}
这将按应有的方式打印70
(十六进制(。
相关文章:
- 在c++中访问int到类对象的映射时出错
- 如何访问矢量<int>到 int 的映射?
- 如何在C++中访问有序映射中的键的范围/间隔?
- 当键值是 std 向量时,为什么使用 at in C++ 访问映射值如此缓慢?
- 映射唯一值和重复值的有效方法.可以访问键或值的位置
- 访问包含矢量对的映射的值
- 线程时访问静态映射时出现隔离错误
- 从具有成对的映射中访问值
- C++ 将元素分配给映射值时访问错误
- CPP 使用不存在的键访问映射
- 访问映射中的分区向量
- 内存映射文件访问非常慢
- 数组中未映射的内存访问从python传递到c++
- 尝试通过指针映射访问类成员
- 矢量 C++ 中的访问映射
- 是否可以访问非线程安全容器内指针指向的值(线程安全映射中的条目)?
- 使用原子指令确保映射访问安全,是否可以使用两个不同的原子对指令进行重新排序
- C++ - 通过 getter 函数在单独的类中从对象指针映射访问成员函数
- 带结构体的列表映射(包含列表)——不能通过映射访问结构体中的列表
- win32或boost内存映射访问