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?
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.
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.
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().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With