Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vector copy constructor C++ : does it have to be linear time?

Tags:

c++

vector

I have a vector containing objects of type STL map, and I do vector.push_back(some map).

This unfortunately calls the map copy constructor, and wastes a lot of time. I understand that i can get around this by keeping a vector of (smart) pointers to maps - but this got me wondering - I read that STL anyway keeps its data on the heap and not on the stack - so why is the copy ctor not O(1) time, by simply copying pointers?

like image 244
dan12345 Avatar asked Apr 13 '26 23:04

dan12345


1 Answers

If you don't need the original map anymore after pushing back a copy back into the vector, write:

some_vector.push_back(std::move(some_map));

If you don't have a C++11 compiler yet, add an empty map and then swap that with the original:

some_vector.resize(some_vector.size() + 1);
some_vector.back().swap(some_map);
like image 155
fredoverflow Avatar answered Apr 16 '26 14:04

fredoverflow