如何打印元素的地图内部的矢量

How to print element of the map inside the vector?

本文关键字:地图 内部 元素 何打印 打印      更新时间:2023-10-16

我想在vector内部的map中打印值和键。

我在互联网上搜索如何打印地图中的元素,但没有找到结果。怎么做呢?

以下是我的代码。

#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.
    }
}

*it将包含您的map,因此也要循环遍历这些迭代器

 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;
    }
}