类中的 C++ 映射不保存新键

Sau*_*ing 0 c++ dictionary class key member

基本上我有一个包含我也定义的结构映射的类。在类中,我有一个成员函数来创建一个新结构并将其添加到映射中(以 aconst char*作为键)。出于某种原因,我的地图似乎只存储了最近添加的键,但它确实存储了正确的值。

这是我的相关代码的片段:

#include <map>
struct PlotData{
    int item_count;
    PlotData(){
        item_count = 0;
    }
};

Class PlotConfig{
public:
    std::map <const char*, PlotData> plots;

    void add_set(const char* key){
        plots[key] = PlotData();

        // added prints to see what's going on
        printf("Printing all plot names... Key is %s\n", key);
        for (std::map<const char*, PlotData>::iterator it=plots.begin(); it!=plots.end(); ++it){
            printf("Key: %s, Items at key: %d\n", it->first, it->second.item_count);
        }
        printf("Done\n)

    }
    void delete_set(const char* key){
        plots.erase(key);
    }
}
Run Code Online (Sandbox Code Playgroud)

我实际上将它包装在 cython 中并使用自定义 imgui 库从 python 中调用它可能是相关的,该库也包装在 cython 中,但基本上,从我的 python 中,我可以这样调用:

conf = PlotConfig()
conf.add_set("First")
conf.add_set("Second")
conf.add_set("Third")
Run Code Online (Sandbox Code Playgroud)

我得到了输出

Printing all plot names... Key is First
Key: First, Items at key: 0
Done

Printing all plot names.. Key is Second
Key: , Items at key: 0
Key: Second, Items at key: 0
Done

Printing all plot names.. Key is Third
Key: , Items at key: 0
Key: , Items at key: 0
Key: Third, Items at key: 0
Done
Run Code Online (Sandbox Code Playgroud)

如果人们好奇的话,有一个中间 cython 类实际上包装了 PlotConfig 及其函数,当我从 Python 传递一个密钥时,在 cython 中,我将key.encode('UTF-8')其编码为字节字符串,以便在 C++ 中使用。无论如何,我的密钥似乎只是暂时存储。当我delete_set()用钥匙打电话时,它没有正确删除,因为它没有看到钥匙。

任何想法发生了什么?

Nut*_*ker 6

如果要使用char *,则需要为地图提供一个比较函子。否则,它将比较指针,而不是它指向的以空字符结尾的字符串。

像这样的东西:

struct cmp {
   bool operator()(char const *a, char const *b) const {
      return std::strcmp(a, b) < 0;
   }
};

std::map<const char *, PlotData, cmp> myMap;
Run Code Online (Sandbox Code Playgroud)

char *用作键时的另一个问题(如其中一条评论中所指出的)是存储指针仅执行浅拷贝,并且输出显示指向的数据超出范围。

如果您希望您的密钥以空字符结尾,我建议std::string改用。