gpt4 book ai didi

c++ - Unordered_map 有效但 Unordered_map 无效

转载 作者:行者123 更新时间:2023-11-30 01:17:57 29 4
gpt4 key购买 nike

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

// 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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com