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;
}
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.
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.
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]) );
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