C++ map 输出格式化垃圾

标签 c++ dictionary format

我有一个 std::map<char*,std::map<char*, char*>> ini;我读入了一个 ini 文件。

Ini 文件的格式为:

[SECTIONAME]
key=value
[SECTIONNAME2]
key2=value2

所以基本上是map<sectionName, map<key, value>> .

我将值很好地插入到 map 中,看起来:

std::cout << "inserting at section: '" << currentSection.c_str() << "', tag: '" << tag.c_str() << "', value: '" << value.c_str() << "'" << std::endl;  
ini.find(const_cast<char *>(currentSection.c_str()))->second.insert(std::make_pair(const_cast<char *>(tag.c_str()), const_cast<char *>(value.c_str())));
std::cout << "inserted key: '" << ini.find(const_cast<char *>(currentSection.c_str()))->second.find(const_cast<char *>(tag.c_str()))->first << "'" << std::endl;
std::cout << "inserted value: '" << ini.find(const_cast<char *>(currentSection.c_str()))->second.find(const_cast<char *>(tag.c_str()))->second << "'" << std::endl;

似乎一切顺利:

inserting at section: 'SCENARIO', tag: 'id', value: '1'
inserted key: 'id'
inserted value: '1'
inserting at section: 'SCENARIO', tag: 'base', value: '1'
inserted key: 'base'
inserted value: '1'

我迭代并打印出值:

std::map<char*, std::map<char*, char*>>::iterator iter;
for(iter = ini.begin(); iter != ini.end(); iter++) 
{
    std::map<char*, char*> innermap = iter->second;
    std::map<char*, char*>::iterator iterinner; 
    std::cout << "found section: '" << iter->first << "'" << std::endl;
    for(iterinner = innermap.begin(); iterinner != innermap.end(); iterinner++) 
    {
        std::cout << "key: '" << iterinner->first << "', value: '" << iterinner->second << "'" << std::endl;
    }
}

在我遍历它并打印出来之后,我得到了这个:

found section: 'á♦╧'
key: '', value: ''
key: 'Φ↑╧', value: ''

为什么我在迭代中得到垃圾?感谢您的帮助!

最佳答案

不要使用指针作为键,因为它是真正的指针,而不是它指向的东西。如果您想使用字符串作为键,请使用 std::string

我当然建议您也使用 std::string 作为内部映射中的数据。

存储指针,尤其是像您看起来那样存储指向临时数据的指针,是导致灾难和未定义行为的秘诀。

关于C++ map 输出格式化垃圾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18130225/

相关文章:

C++ <iostream.h> 错误

c# - 字典 ArgumentException 日志重复键 : which is more performant?

c++ - 为什么 std::map::operator[] 的复杂度相对于键数是对数的?

json - 将文本转换为 JSON

python - 如何在python中通过多种格式格式化日期字符串

c++ - 比较保存十六进制值的 Char C++

c++ - 如何使 '<?=' 可用于 C++?

delphi - Delphi秒表时间格式

c++ - 使用 require(..) 或 dofile(..) 在 Lua 中加载 .dll

java - 覆盖哈希码方法时的HashMap性能