Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy vector to map in STL in a graceful way

Currently, I have some data in a vector. currently, I want to transform the vector to a map.
So it will be organize as below(N is even number).

vector: element 1, element 2, element 3, element 4 ... element N.

map: key1: element 1, value1: element 2, key2: element 3 value2: element 4...

Currently, I just enumerate vector, is there any other graceful way to do it. C++11 is prefer. Thanks.

for (int x = 0; x < vec.size(); )
{
    map[vec[x]] = vec[x+1];
    x+=2;
}
like image 235
Jerry YY Rain Avatar asked Apr 24 '14 03:04

Jerry YY Rain


People also ask

Does Push_back make a copy?

When inserted using the push_back, the new element is copy-or-move-constructed. The insertion could be inefficient if the passed argument to the push_back is a temporary because the temporary is constructed, copied/moved, and destroyed.

How are vectors implemented in STL?

Vector is implemented as a dynamically allocated array. The memory for this array is allocated in the constructor. As more elements are inserted the array is dynamically increased in size. A constructor without parameter creates an array with a default size.


1 Answers

Your code works (noting Michael J's suggestion to not process the last element if there is an odd number).

There is a small improvement that can be made. The call map[vec[x]] constructs an entry using the default constructor of the value_type, and then the copy-assignment operator copies the value from vec[x+1].

You could avoid the copy-assignment step by doing:

the_map.insert( std::make_pair(vec[x], vec[x+1]) );

I think this ends up having the map entry copy-constructed from the pair. In C++11 you can do:

the_map.emplace(vec[x], vec[x+1]);

which allows the compiler to minimize the amount of copying done. If your object supports move semantics and you want to destroy the vector afterwards, you can even go:

the_map.emplace( std::move(vec[x]), std::move(vec[x+1]) );
like image 166
M.M Avatar answered Oct 08 '22 09:10

M.M