Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating a map from two vectors

Tags:

c++

map

stl

vector

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 that in the most simple way?

like image 489
lital maatuk Avatar asked Feb 09 '11 14:02

lital maatuk


People also ask

Can we create a map of vector in C++?

Map of Vectors in STL: Map of Vectors can be very efficient in designing complex data structures. Syntax: map<key, vector<datatype>> map_of_vector; OR map<vector<datatype>, key> map_of_vector; For example: Consider a simple problem where we have to check if a vector is visited or not.

Can we use vector as a key in map?

In C++ we can use arrays or vector as a key against to a int value like: map<vector<int> ,int > m; Can I do same in MATLAB by containers.


1 Answers

Here is a solution that uses standard library functions (and C++0x lambdas).

const int data1[] = { 0, 2, 4, 6, 8 };
const int data2[] = { 1, 3, 5, 7, 9 };
std::vector<int> vec1(data1, data1 + 5);
std::vector<int> vec2(data2, data2 + 5);
std::map<int,int> map;

// create map
std::transform(vec1.begin(), vec1.end(), vec2.begin(), std::inserter(map, map.end()), [](int a, int b)
{
    return std::make_pair(a, b);
});

// display map
std::for_each(map.begin(), map.end(), [](const std::pair<int,int>& p)
{
    std::cout << p.first << "," << p.second << "\n";
});

Note: This assumes vec1.size() is not greater than vec2.size().

like image 50
Blastfurnace Avatar answered Sep 17 '22 15:09

Blastfurnace