简体   繁体   中英

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

#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. 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:

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

See it in action here: 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).

You can use the set constructor that takes the map as a range.

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

If your set already exists, then you can use copy .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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