如何在C++中打印矢量<map<string,int> >

How to print vector<map<string, int> > in C++

本文关键字:lt gt map int string C++ 打印      更新时间:2023-10-16

vector < map< string, int > >类型中。

当我知道向量的索引时,我只想打印出map的字符串,但它不起作用。

错误发生在

cout<< myVec.at(intTmp)->first<<"n";

我不确定如何访问矢量内部的地图。

#include <iostream>
#include <string>
#include <map>
#include <vector>
using namespace std;
int N, M;
vector<map<string, int> > myVec;
bool isDigits(string& s){
for(int i=0; i<s.size(); ++i){
if(!isdigit(s[i])) return false;
}
return true;
}

int main()
{
cin >> N >> M;
for(int i=1; i<=N; ++i){
string tmp;
cin.clear();
getline(cin, tmp);
myVec.emplace_back(tmp, i);
}
for(int i=1; i<=M; ++i){
string tmp1;
cin.clear();
getline(cin, tmp1);
if(isDigits(tmp1)){
int intTmp = atoi(tmp1.c_str());
cout<< myVec.at(intTmp)->first<<"n";
}
}
return 0;
}

使用此代码片段:

for(auto map2:myVec)
{   
for(auto it = map2.begin();it != map2.end();it++)
cout << (it->first).c_str() << " " << it->second <<endl;
}

这是一张你必须迭代地图的地图

vector< map<string,int> > myVec;
for( int i=0; i< myVec.size(); i++) {
for(auto it = myVec[i].begin(); it != myVec[i].end(); it++) {
cout<<it->first;
}
}