首页 > 解决方案 > 使用一个键和一对值遍历映射

问题描述

我有这张地图,并假设它已经充满了数据。

map<string,pair<int,int> >mymap;

假设它有键和一对看起来像这样的值:

前任: "Hello", {10,20};

我已经知道如何一键一值输出。

std::map 一个键,两个值这里显示了一个键可以有 2 个值,但我不知道如何遍历它们并获得示例中的输出。

标签: c++

解决方案


所以这对我有用。

我首先初始化了这些。

pair<int,int> pairs;
map<string, pair<int,int> > mymap;

然后使用 for 循环。

pairs.first = //some integer;
pairs.second = //some integer; 
mymap[ //here i used the values from an array so i used array[current_index] ] = pairs;

为输出。

for(auto i : mymap) {
    //i.first for the key
    //i.second.first and i.second.second for the pair values
}

我阅读的资料来源:

遍历pair的向量https://www.cplusplus.com/reference/unordered_map/unordered_map/insert/

请务必通知我。也许我对这个不正确。


推荐阅读