我已经声明了一个关联数组,现在要打印它:
#include <map>
#include <string>
#include <cstdio>
using namespace std;
int main() {
map<string, int> m;
m["Peter"] = 4;
m["John"] = 3;
m["Katie"] = 3;
map<string, int>::iterator curr,end;
for(curr = m.begin(), end = m.end(); curr != end; curr++) {
printf("%s : %i\n", curr->first, curr->second);
}
return 0;
}
我的编译器出现错误:
main.cpp: In function ‘int main()’:
main.cpp:24: warning: cannot pass objects of non-POD type ‘const struct std::basic_string<char, std::char_traits<char>, std::allocator<char> >’ through ‘...’; call will abort at runtime
令人惊讶的是——这是真的——调用在运行时中止...
但我不知道为什么...我应该修复什么? “通过‘...’”到底是什么意思?
最佳答案
在 C++ 中使用 std::cout
,尤其是在 STL 中:
std::cout << curr->first << " : " << curr->second << std::endl;
顺便说一句,不需要定义另一个名为“end”的变量。所以你可以像这样重写你的 for
循环:
for(map<string, int>::iterator curr = m.begin(); curr != m.end() ; curr++)
{
std::cout << curr->first << " : " << curr->second << std::endl;
}
关于c++ - 在 C++ 中打印关联数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4601930/