c++ - 在 C++ 中打印关联数组

标签 c++ arrays associative-array

我已经声明了一个关联数组,现在要打印它:

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

相关文章:

C++ API 设计 : is using void* a bad idea?

c++ - 将反向存储在整数c++中

c++ - 使用多个排序键实现排序的自定义比较器

JavaScript:数组排序优化

Bash:将值添加到关联数组,而 key=>value 已经存在

c++ - Ogre3d 的 Fmod 包装器(soundManager)问题

c++ 中的 java.lang.Field 等价物

ios - 我可以从数组中的第二个元素开始填充我的表格 View 吗? ( swift )

oracle - 为什么在 PL/SQL 中检查空关联数组会失败?

php - 如何获取json数组并插入数据库。 php