c++ - How to copy vector to map in STL in a graceful way -
Currently, I have some data in vector. Currently, I want to convert the vector to a map.
So it will be arranged in the form of below (N is also the number)
Vector: element 1, element 2, element 3, element 4 ... element N.
map: key 1: element 1, value1: element 2, key 2: Element 3 value 2: element 4 ...
Currently, I just show vector, there is no other great way to do this. C ++ 11 priority is thanks.
for (int x = 0; x & lt; vec.size ();) {map [vec [x]] = vec [x + 1]; X + = 2; }
Your code works (keeping in mind the suggestion of Michael J. There is a strange number not the process of the last element).
There is a small improvement that can be made. The call creates an entry using the default constructor of the map value_type , and then the cost-per-assignment operator value to vec [X + 1] . You can avoid the counter-assignment step by doing this:
the_map.insert (std :: make_pair (vec [x], vec [x + 1]) ); I think it ends up making a map entry copy from the pair. In C ++ 11 you can:
the_map.emplace (vec [x], vec [x + 1]); which allows the compiler to reduce the amount to be copied. If your object supports the transfer of semantics and you want to delete the vector later, you can go here:
the_map.emplace (std :: move (vec [ x]), std :: move vec [x + 1]));
Comments
Post a Comment