C++ 无序地图<;字符串,int>;工作正常但无秩序的地图<;字符串,字符串>;不
我不明白为什么这个简短示例中的第二块代码不能正确编译。我的理解是,中的第二个参数表示值,它不需要是唯一的。为什么第二个代码块抛出编译器错误,我需要做什么来纠正它C++ 无序地图<;字符串,int>;工作正常但无秩序的地图<;字符串,字符串>;不,c++,unordered-map,C++,Unordered Map,我不明白为什么这个简短示例中的第二块代码不能正确编译。我的理解是,中的第二个参数表示值,它不需要是唯一的。为什么第二个代码块抛出编译器错误,我需要做什么来纠正它 // Unordered Map example .cpp #include <stdio.h> #include <string> #include <cstring> #include <unordered_map> using namespace std; int main(v
// 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;
}
这些都是我得到的错误
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’
map_example.cpp:在函数“int main()”中:
map_example.cpp:20:警告:无法通过“…”传递非POD类型“struct std::basic_string”的对象;调用将在运行时中止
map_example.cpp:20:警告:格式“%s”要求类型为“char*”,但参数2的类型为“int”
如果我在一个基本的C++类中遇到这样的一个STD:string,我需要做什么才能将一个自定义类作为一个值,在哪里可以找到一个完全实现的最小的例子?
Primf不适用于STD::String。使用
coutprintf不能与std::string一起使用。要么使用coutprintf(“%s\n”,m1[“foo”)代码>是C
对于C++,您应该使用<代码> STD::CUT使字符串和INTMAP的值都按预期打印出来。
编译器无法将std::string
对象自动转换为const char*
(默认情况下没有转换为const char*
)printf(“%s\n”,m1[“foo”)代码>是C
对于C++,您应该使用<代码> STD::CUT使字符串和INTMAP的值都按预期打印出来。
编译器无法将std::string
对象自动转换为const char*
(默认情况下没有转换为const char*
)clang会给出更好的错误消息:clang会给出更好的错误消息:他用%i打印了int。我看不到从int到char*的转换。这也不会自动发生。他用%i打印int。我看不到从int到char*的转换。而且,这不会自动发生。
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’