将两个向量的对转换为相应元素的映射

Aka*_*all 3 c++ stl c++11

我想转换std::pair<std::vector<int>, std::vector<double>>std::map<int, double>.

例如:

// 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}};
Run Code Online (Sandbox Code Playgroud)

我可以通过以下功能实现此目的.但是,我觉得必须有更好的方法来做到这一点.如果是这样的话是什么?

#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;
}
Run Code Online (Sandbox Code Playgroud)

Pio*_*cki 7

是的,还有更好的方法:

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); });
Run Code Online (Sandbox Code Playgroud)

演示1

甚至没有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&>);
Run Code Online (Sandbox Code Playgroud)

演示2

或者以C++ 03的方式:

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

演示3

输出:

2 : 4.3
3 : 5.1
4 : 6.4
Run Code Online (Sandbox Code Playgroud)