【问题标题】:How to copy keys and values of map to set of pair如何将映射的键和值复制到一对集合
【发布时间】:2020-04-16 14:10:31
【问题描述】:

大家好,我正在尝试将我的数据从地图传输到配对集合 这是我的测试代码

#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 循环完成且地图已填满时。如何传输数据或将其复制到该组对?

提前谢谢你

【问题讨论】:

  • 在循环后定义集合:set&lt; pair&lt;string, int&gt; &gt; s{map.begin(),map.end()};

标签: c++ dictionary stl set


【解决方案1】:

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

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

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

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

【讨论】:

    【解决方案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()));
    

    【讨论】:

    • 感谢它的所有工作。但我的想法是获取输入,例如 John 23 Peter 44 和 Rick 65,我想像输入一样将其传输到按此顺序设置并以相同的方式打印?但我不知道如何使它不工作并使用一对?
    • 看来你需要unordered_mapunordered_set
    • 为什么我需要 unordered_map 或 unordered_set ?我不明白我选择集合是因为​​我需要独特的元素
    • 无论哪种方式,您都会获得独特的元素。在unordered_ 版本中,唯一元素按照它们插入的顺序排列。
    • @cigien In the unordered_ versions, the unique elements are in the order they were inserted 没有。顾名思义,元素是无序的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-17
    • 2018-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-26
    相关资源
    最近更新 更多