creating a map from two vectors

前端 未结 5 1094
旧时难觅i
旧时难觅i 2020-12-17 23:32

If I have two stl vectors vect1, vect2 and I want to produce from them a map, so first element from vect1 will correspond to first element in vect2 and so on. How can I do t

5条回答
  •  南方客
    南方客 (楼主)
    2020-12-17 23:57

    We will use the version of std::transform that takes 2 input sequences. (Not as well known it appears as the one that takes a single sequence).

    You can pass in std::make_pair as your transformer (op) thus in your case

    std::vector vec1, vec2;
    std::map< int, int > mergedMap;
    std::transform( vec1.begin(), vec1.end(), vec2.begin(), 
           std::inserter(mergedMap, mergedMap.end() ), std::make_pair );
    

    I have tested the code and it compiles fine with GNU 4.3.2

    (I have also tested now with C++11. It works when I changed make_pair to take int const& rather than int).

    If the two input sequences are of different length, it will be fine if the first is shorter, and later elements in the second sequence will be ignored. If the first is longer, it will produce undefined behaviour.

提交回复
热议问题