我正在尝试转换 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); });
甚至没有 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
关于c++ - 将两个 vector 对转换为相应元素的映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25941248/