C++中如何输出vector<map<string, int>>?嵌套容器访问报错求解
解决vector<map<string, int>>的访问错误问题
嘿,我来帮你搞定这个问题!你代码里的错误主要出在两个细节上,我给你拆解清楚:
1. 引用与指针的访问符号搞混了
vector::at()方法返回的是容器指定位置元素的引用,不是指针!所以你不能用->来访问成员,得换成.。比如你原来写的myVec.at(intTmp)->first,第一步要把->改成.。
2. 直接对map用first是错误的
map是键值对的集合,first是map迭代器指向的键值对元素的成员(对应键),你不能直接对map对象调用first。如果想打印这个map里的键,要么取第一个元素的键,要么遍历整个map打印所有键。
修正后的代码示例
比如你想打印vector中索引intTmp位置的map里的所有键,可以这么写:
#include <iostream> #include <string> #include <map> #include <vector> using namespace std; int main() { vector<map<string, int>> myVec; // 先给容器塞点测试数据 map<string, int> testMap = {{"apple", 1}, {"banana", 2}, {"cherry", 3}}; myVec.push_back(testMap); int intTmp = 0; // 假设要访问第0个元素 // 遍历map打印所有键 cout << "Map at index " << intTmp << " has keys:" << endl; for (const auto& pair : myVec.at(intTmp)) { cout << pair.first << "\n"; } // 如果只想打印第一个键(要先判断map非空,避免越界) if (!myVec.at(intTmp).empty()) { cout << "First key: " << myVec.at(intTmp).begin()->first << endl; } return 0; }
关键修正点拆解
- 把错误的
myVec.at(intTmp)->first改成myVec.at(intTmp).begin()->first(获取第一个键) - 如果要遍历所有键,用范围for循环直接遍历
myVec.at(intTmp)这个map对象,每个循环元素是pair<const string, int>,pair.first就是对应的键
这样就能正确访问vector里的map并打印键啦!
内容的提问来源于stack exchange,提问作者Ray
相关产品推荐
相关产品推荐

