簡體   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