2014-09-19 91 views
3

我試圖將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; 
} 
+0

我目前正在嘗試'boost :: zip_iterator',但似乎有涉及的boost類型(如'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。第二個))};'(zip迭代器將返回一個pair/tuple,它可以用來構造要返回的map的值類型) – dyp 2014-09-19 20:20:48

+0

@dyp Jonathan Wakely [有一個非常好的'zip_iterator'包裝器] http://stackoverflow.com/a/10457201/2756719)。 – 2014-09-19 20:26:49

+0

@ T.C。根本問題似乎是'tuple'不能轉換爲'pair'。 'zip_iterator'(必然)有'tuple'的操作符,而'map'只處理'pair'(它的值類型)。 – dyp 2014-09-19 20:56:23

回答

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

DEMO 1

甚至沒有拉姆達:

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 
+1

TBH我發現這比原來的可讀性差。 – 2014-09-19 20:07:16

1

隨着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

即使兩個向量的長度不同,這也具有安全性的好處。

相關問題