std::在C++上映射问题

std::map question on C++

本文关键字:映射 问题 C++ std      更新时间:2023-10-16

我对c++:上的std::map有不确定性

我做了一个对象C_Configuration,它加载了一个链接库(.so)C_ConfigurationLibrary

C_Configuration类具有std::map,而The C_ConfigurationLibrary具有初始化std::map的方法。

如果我使用"for"循环从C_Configuration访问std::map

std::map<const char*, const char*>::iterator l_item;
for(l_item = m_configuration_map.begin();
    l_item != m_configuration.end();
    l_item++)

这是可以的;

但如果我使用:

m_configuration[VALUE_KEY] // the value is NULL

这不好;

我的代码:

C_Configuration::C_Configuration()
{
    m_configuration = LoadLibrary(); // load the linked library (.so)
    if(m_configuration != NULL)
    {
        // DEBUG
        LOG_DEBUG("Loading Key from plugin...");
        m_configuration->LoadKeys(m_configuration_map);
        std::map <const char*, const char*>::iterator l_item;
        for ( l_item = l_configuration_map.begin();
              l_item != l_configuration_map.end();
              l_item++ )
        {                
            //THIS IS OK             
        }
        m_configuration_map[FIRST_KEY] // THIS IS NOT OK
    }
}
void C_ConfigLibrary::LoadKeys(std::map<const char*, const char*>& p_configuration_map)
{
    // DEBUG
    LOG_DEBUG("Loading Keys...");
    p_configuration_map.insert ( std::make_pair<const char*, const char*>(FIRST_KEY, FIRST_VALUE) );
    // DEBUG
    LOG_DEBUG("Loaded Key DBUS used: %s",m_dbus_used.c_str());
    p_configuration_map.insert ( std::make_pair<const char*, const char*>(SECOND_KEY,SECOND_VALUE) );
}

你能帮我吗?

非常感谢

您使用const char* s作为键,但比较指针的是它们的内存地址,而不是它们所指向的文本。因此,当共享库中有一个字符串文字,而主应用程序对象中的字符串文字中有相同的文本时,它们可能具有不同的地址,并且不会作为键进行比较。

您最好使用std::strings作为密钥,尽管使用const char*作为值是安全的。

FWIW,如果您使用const char*作为键,不仅来自不同翻译单元的字符串文字有时会像这样挑剔,而且您将很难使用来自本地缓冲区的文本,甚至是std::string.c_str()返回值——这是一个非常糟糕的主意。

FIRST_KEY是否真的存在,或者您只是用它作为一个例子来表明您希望元素位于给定的键上?

它可能不起作用,因为您将C字符串存储为std::map的密钥。它们是根据各自的地址进行比较的,而不是字符串的实际内容,这可能是它失败的原因。您应该使用std::string作为映射的密钥。

不过,您应该发布实际的代码,否则您只能期待猜测工作。很明显,这段代码并不是全部,因为您使用的是FIRST_KEY等,而我们不知道它们是什么,而且括号的数量不匹配,而且语句不完整,会产生错误。