简体   繁体   中英

Convert pair of two vectors to a map of corresponding elements

I am trying to convert std::pair<std::vector<int>, std::vector<double>> to std::map<int, double> .

For example:

// I have this:
std::pair<std::vector<int>, std::vector<double>> temp =
                            {{2, 3, 4}, {4.3, 5.1, 6.4}};
// My goal is this:
std::map<int, double> goal = {{2, 4.3}, {3, 5.1}, {4, 6.4}};

I can achieve this with the following function. However, I feel like there must be a better way to do this. If so what is it?

#include <iostream>
#include <vector>
#include <utility>
#include <map>

typedef std::vector<int> vec_i;
typedef std::vector<double> vec_d;

std::map<int, double> pair_to_map(std::pair<vec_i, vec_d> my_pair)
{
    std::map<int, double> my_map;
    for (unsigned i = 0; i < my_pair.first.size(); ++i)
    {
        my_map[my_pair.first[i]] = my_pair.second[i];
    }
    return my_map;
}

int main()
{

    std::pair<vec_i, vec_d> temp = {{2, 3, 4}, {4.3, 5.1, 6.4}};

    std::map<int, double> new_map = pair_to_map(temp);

    for (auto it = new_map.begin(); it != new_map.end(); ++it)
    {
        std::cout << it->first << " : " << it->second << std::endl;
    }
    return 0;
}

Yes, there is a better way:

std::transform(std::begin(temp.first), std::end(temp.first)
             , std::begin(temp.second)
             , std::inserter(new_map, std::begin(new_map))
             , [] (int i, double d) { return std::make_pair(i, d); });

DEMO 1

or even without a lambda:

std::transform(std::begin(temp.first), std::end(temp.first)
             , std::begin(temp.second)
             , std::inserter(new_map, std::begin(new_map))
             , &std::make_pair<int&, double&>);

DEMO 2

or in a C++03 fashion:

std::transform(temp.first.begin(), temp.first.end()
             , temp.second.begin()
             , std::inserter(new_map, new_map.begin())
             , &std::make_pair<int, double>);

DEMO 3

Output:

2 : 4.3
3 : 5.1
4 : 6.4

With Boost's range algorithm extensions :

#include <boost/range/algorithm_ext/for_each.hpp>

boost::for_each(temp.first, temp.second, [&](int i, double d) { new_map[i] = d; });

Demo .

This also has the benefit of being safe even if the length of the two vectors are different.

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