Say I have a situation where I'm populating a vector/list iteratively, and I don't know how many elements there will be beforehand. For example, the code might look more or less like this:
std::vector<MyClass> mythings;
for(int i = 0; i < *some number*; ++i){
if(*some condition here*){
mythings.push_back(MyClass());
}
}
I know that push_back
isn't very efficient when used for std::vector
. So in the above chunk of code I could change mythings
to a std::list
, and presumably that would be faster, since std::list
is implemented as a linked list. However, say that I know that I'll need to do random access on the list/vector I just created. For random access, std::vector
would be much faster. So using std::vector
and std::list
both have their disadvantages in this scenario.
In this situation, would it be more efficient for me to use a std::list
when creating the list/vector, and then convert it to a std::vector
afterwards (for example, as in this question: One liner to convert from list<T> to vector<T>) so that I can take advantage of the random access of std::vector
? Or would the cost of the conversion outweigh the gain?