【问题标题】:Convert pair of two vectors to a map of corresponding elements将两个向量对转换为对应元素的映射
【发布时间】:2014-09-19 19:38:32
【问题描述】:

我正在尝试将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;
}

【问题讨论】:

  • 我目前正在尝试boost::zip_iterator,但所涉及的提升类型(如boost::tuple)和StdLib 类型(如std::pair)之间似乎不兼容。可以为 StdLib 类型重写 zip-iterator 以将其分解为 return {make_zip_iterator(begin(p.first), begin(p.second)), make_zip_iterator(end(p.first), end(p.second))};(zip 迭代器将返回可用于构造要返回的映射的值类型的对/元组。)
  • @T.C.根本问题似乎是tuple 不能转换为pairzip_iterator(必然)带有tuples 的运算符,而map 只处理pairs(它的值类型)。

标签: c++ c++11 stl


【解决方案1】:

是的,有更好的方法:

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

甚至没有 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

或以 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>);

DEMO 3

输出:

2 : 4.3
3 : 5.1
4 : 6.4

【讨论】:

    【解决方案2】:

    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.

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-01
      • 2019-05-12
      • 1970-01-01
      相关资源
      最近更新 更多