c++ - Unordered_map<string, int> 有效但 Unordered_map<string, string> 无效

标签 c++ unordered-map

我不明白为什么这个简短示例中的第二个代码块无法正确编译。我的理解是 <> 中的第二个参数表示值,它不需要是唯一的。为什么第二个代码块抛出编译器错误,我需要做什么来补救它?

// Unordered Map example .cpp

#include <stdio.h>
#include <string>
#include <cstring>
#include <unordered_map>

using namespace std;

int main(void) {

    // This works as expected
    unordered_map<std::string, int> m;
    m["foo"] = 42;
    printf("%i\n", m["foo"]);

    // This this doesn't compile
    unordered_map<std::string, std::string> m1;
    m1["foo"] = "42";
    printf("%s\n", m1["foo"]);

    return 0;
}

我正在使用 CentOS 5.8 编译这段代码

g++44 -c -Wall -std=c++0x -g map_example.cpp

这些是我得到的错误

map_example.cpp: In function ‘int main()’:
map_example.cpp:20: warning: cannot pass objects of non-POD type ‘struct std::basic_string<char, std::char_traits<char>, std::allocator<char> >’ through ‘...’; call will abort at runtime
map_example.cpp:20: warning: format ‘%s’ expects type ‘char*’, but argument 2 has type ‘int’

如果我在使用基本的 c++ 类(如 std:string)时遇到问题,我需要做什么才能将自定义类作为值,我在哪里可以找到完全实现的最小示例?

最佳答案

printf 不适用于 std::string。要么使用 cout << m1["foo"]printf("%s", m1["foo"].c_str())

关于c++ - Unordered_map<string, int> 有效但 Unordered_map<string, string> 无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23358628/

相关文章:

python - 将 Python 添加到 C++ : not finding Python. h

c++ - boost 路口

c++ - Qt layout和splitter的区别

c++ - 对于 std::tr1::unordered_map,是否有任何类似于 std::map::lower_bound 的等效 std::algorithm?

C++ - 在 unordered_map 中使用多个值作为键的最佳方式

c++ - 没有任何内置库的 C++ 中浮点值的小数部分

c++ - 在 C++ 中是否有一个由时间控制的循环?

c++ - 如何将 const unordered_map 中的值分配给另一个 const 变量 - C++

c++ - unordered_map 插入失败

c++ - 定时 vector vs map vs unordered_map 查找