std::在C++上映射问题
std::map question on C++
我对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::string
s作为密钥,尽管使用const char*
作为值是安全的。
FWIW,如果您使用const char*
作为键,不仅来自不同翻译单元的字符串文字有时会像这样挑剔,而且您将很难使用来自本地缓冲区的文本,甚至是std::string
的.c_str()
返回值——这是一个非常糟糕的主意。
FIRST_KEY
是否真的存在,或者您只是用它作为一个例子来表明您希望元素位于给定的键上?
它可能不起作用,因为您将C字符串存储为std::map
的密钥。它们是根据各自的地址进行比较的,而不是字符串的实际内容,这可能是它失败的原因。您应该使用std::string
作为映射的密钥。
不过,您应该发布实际的代码,否则您只能期待猜测工作。很明显,这段代码并不是全部,因为您使用的是FIRST_KEY
等,而我们不知道它们是什么,而且括号的数量不匹配,而且语句不完整,会产生错误。
- AIX C++映射编译问题
- 在c++中擦除后在映射上迭代时出现的奇怪问题
- 在 C++ 中使用静态映射的奇怪问题
- 一维数组映射方式的性能差异问题
- QlineEdit的信号映射问题
- 使用集合和映射来解决模式问题
- 在将平截头体从摄影机空间转换为灯光空间以进行阴影映射方面存在主要问题
- 使用成员函数指针作为键C++映射时出现问题
- 无序映射的问题
- 我的 lambda 表达式进行映射键比较有什么问题?
- 将 std 绑定传递到函数映射的问题
- 打开文件映射问题,找不到文件映射
- 标准::映射插入/擦除的并发问题
- 删除元素时使用 STL 映射的迭代器时遇到问题
- 在 C 语言中打印映射/过滤器/减少函数时出现问题
- 映射问题
- 参数"Global\MyMapping"的创建文件映射问题
- std::在C++上映射问题
- 普通映射问题
- stl:映射问题