sclee1 sclee1 - 1 month ago 4
C++ Question

How to print element of the map inside the vector?

I want to print the values and keys in the map inside the vector.

I searched for how to print the elements in the map on the Interent, but no results were found. How to do so?

Below are my codes.

#include <iostream>
#include <string>
#include <map>

using namespace std;
vector<map<string,int>> list;
vector<map<string, int>>::iterator it;

int N;
int M;

int main(void) {
cin >> N;

string s;
int num = 0;

for (int i = 0; i < N; ++i) {
scanf("%s,%d", s, &num);
map<string, int> product;
product.insert(pair<string, int>(s, num));
list.push_back(product);
}

for (it = list.begin(); it != list.end(); ++it) {
//I don't know how to print the elements in the map.
}
}

Answer

*it will contain your map, so loop over those iterators too

 for (it = list.begin(); it != list.end(); ++it) {
    for (map<string, int>::iterator mapIt(it->begin()); mapIt != it->end(); ++mapIt) {

      // output here
      std::cout << mapIt->first << ", " << mapIt->second << std::endl;
    }
}