繁体   English   中英

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

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

大家好,我正在尝试将我的数据从 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;
}

当 while 循环完成并且 map 被填充时。 如何传输数据或将其复制到该组对?

先感谢您

set 构造函数实际上为你处理了这一切,所以你可以这样做:

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

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

(另外,您可能不应该将变量map为与类型相同的名称。当您using namespace std时,这将是一个更大的问题)。

您可以使用将 map 作为范围的set构造函数

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

如果您的集合已经存在,那么您可以使用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