简体   繁体   English

如何将 map 的键和值复制到对集合

[英]How to copy keys and values of map to set of pair

Hello all i am trying to transfer my data from the map to the set of pair that's my test code大家好,我正在尝试将我的数据从 map 传输到我的测试代码对

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

When the while loop finish and the map is filled.当 while 循环完成并且 map 被填充时。 How to transfer the data or copy it to the set of pair?如何传输数据或将其复制到该组对?

Thank you in advance先感谢您

The set constructor actually handles this all for you, so you can just do: set 构造函数实际上为你处理了这一切,所以你可以这样做:

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

See it in action here: https://ideone.com/Do0LOW在此处查看实际操作: https://ideone.com/Do0LOW

(Also, you probably shouldn't name your variable map the same as a type. This is even more of an issue when you're using namespace std like that). (另外,您可能不应该将变量map为与类型相同的名称。当您using namespace std时,这将是一个更大的问题)。

You can use the set constructor that takes the map as a range.您可以使用将 map 作为范围的set构造函数

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

If your set already exists, then you can use copy .如果您的集合已经存在,那么您可以使用copy

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM