繁体   English   中英

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

[英]Convert pair of two vectors to a map of corresponding elements

我试图将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}};

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

#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;
}

是的,还有更好的方法:

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); });

演示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&>);

演示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>);

演示3

输出:

2 : 4.3
3 : 5.1
4 : 6.4

使用Boost的范围算法扩展

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

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

演示

即使两个矢量的长度不同,这也具有安全的好处。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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