Switching from a list to a vector

Hi there,

I'm using a std::list to store some data, because it's very likely to change frequently. insertions, and deletions are both common.

However at a given point in my program, I want to take a snapshot of the list, and put that to the side. I know this snapshot will ONLY be inspected, and not changed at all. Does it make sense to copy the list into a vector, or just make a copy of the list to be iterated over.

If it helps, I probably will only look at the snapshot 1 or 2 times.

Also, the size of the list will on average be pretty small.
I think a vector makes sense.

You can preallocate the vector which might help performance:

1
2
std::vector<MyData> snapshot(list.size());  //should prevent re-allocation
snapshot.assign(list.begin(), list.end());


Actually, the above will run 2*N constructors (where N = list.size()).

This is more efficient:

1
2
3
std::vector<MyData> snapshot;
snapshot.reserve( list.size() );
snapshot.assign( list.begin(), list.end() );


Alternatively, you can check your STL implementation to see if

 
std::vector<MyData> snapshot( list.begin(), list.end() );


is equally as efficient.

Topic archived. No new replies allowed.