我正在尝试将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 :(得分: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); });
甚至没有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&>);
或以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>);
输出:
2 : 4.3
3 : 5.1
4 : 6.4
答案 1 :(得分: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; });
即使两个向量的长度不同,这也有安全的好处。