c++ - 将两个 vector 对转换为相应元素的映射

标签 c++ c++11 stl

我正在尝试转换 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); });

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

关于c++ - 将两个 vector 对转换为相应元素的映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25941248/

相关文章:

c++ - C++ lambda默认参数编译器是否行为不当?

c++ - 如何计算 std::vector<int>::iterator 和 std::vector<int>::reverse_iterator 之间的距离?

c++ - 在 C++ 中使用 max_element() 和 min_element() 的段错误

c++ - 减少 STL vector 的容量

c++ - SDL2_net emscripten

c++ - 检测到新/删除堆损坏 : CRT detected that the application wrote to memory after end of heap buffer

c++ - 从 64 位整数中提取 32 位

c++ - 创建宏以将 token (参数)一个一个地收集到列表中

c++ - 如何将整个流读入 std::vector?

c++ - 为什么本地类中的字段不能是静态的?