class 中的 C++ 映射未保存新键

C++ map in class is not saving new keys

基本上我有一个 class,其中包含我也定义的结构图。在 class 中,我有一个成员函数来创建一个新结构并将其添加到映射(它以 const 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);
    }
}

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

conf = PlotConfig()
conf.add_set("First")
conf.add_set("Second")
conf.add_set("Third")

我得到了输出

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

如果人们很好奇,有一个中介 cython class 实际上包装了 PlotConfig 及其功能,当我从 Python 传递一个密钥时,在 cython 中,我使用 key.encode('UTF-8') 将其编码为字节字符串,以便在 C++ 中使用。 Aanyways,看来我的密钥只是暂时存储。当我用键调用 delete_set() 时,它没有正确删除,因为它没有看到键。

有什么想法吗?

如果你想使用char *你需要给地图一个比较函子。否则,它比较的是指针,而不是它指向的以 null 结尾的字符串。

像这样:

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

std::map<const char *, PlotData, cmp> myMap;

使用 char * 作为键时的另一个问题(如评论之一所指出的)是存储指针仅进行浅拷贝,输出显示指向的数据超出了范围。

如果您希望您的键是空终止字符串,我建议改用 std::string