【发布时间】: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 迭代器将返回可用于构造要返回的映射的值类型的对/元组。) -
@dyp Jonathan Wakely has a really nice wrapper for
zip_iterator. -
@T.C.根本问题似乎是
tuple不能转换为pair。zip_iterator(必然)带有tuples 的运算符,而map只处理pairs(它的值类型)。