如何将映射的键和值复制到对集

时间:2020-04-16 14:10:31

标签: c++ dictionary stl set

您好,我正在尝试将我的数据从地图转移到配对对中 那是我的测试代码

#include <iostream>
#include <unordered_map>
#include <map>
#include <algorithm>
#include <vector>




using namespace std;

int main() {


    string command;

    int resource;
   map<string, int> map;
   set< pair<string, int> > s;

   while (std::cin >> command && command != "stop" && std::cin >> resource)
    {
        map[command] += resource;

    }


    return 0;
}

while循环结束并且地图被填充时。如何传输数据或将其复制到对中?

提前谢谢

2 个答案:

答案 0 :(得分:2)

set构造函数实际上为您处理了所有这些,因此您可以执行以下操作:

std::set<std::pair<std::string, int>> s(m.begin(), m.end());

在此处查看实际操作:https://ideone.com/Do0LOW

(此外,您可能不应该将变量map的名称与类型相同。当您using namespace std这样的时候,这甚至是一个问题。)

答案 1 :(得分:2)

您可以使用将地图作为范围的set constructor

std::set<std::pair<std::string, int>> s {map.begin(), map.end()};

如果您的设置已经存在,则可以使用copy

std::copy(map.begin(), map.end(), std::inserter(s, s.end()));