如何使用字符串指针访问映射的键

How to access keys of maps using a string pointer

本文关键字:映射 访问 指针 何使用 字符串      更新时间:2023-10-16

我正在尝试使用字符串*指针而不是其实际值来访问地图。 每当我使用此指针时,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">

值用作键。

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(十六进制(。