Giannis
Giannis

Reputation: 39

Is there any faster way to insert elements in a std::vector

I'm trying to insert a string in the following vector: std::vector<std::string> fileVec.

The fileVec already has many elements in it (up to 1 million strings) before I call these lines:

int index = 5;

//there is some code here to find the index i want insert the text (let's take for example has value 5)

fileVec.insert(fileVec.begin() + index, "add this text");

The problem I have is that it take so much time to insert the text (specially if index is a small number).

Is there any faster way to add elements in a big vector (without deleting other elements)?

The fileVec.insert will not be called many times, around 15 times.

Upvotes: 1

Views: 2193

Answers (2)

Vlad Feinstein
Vlad Feinstein

Reputation: 11311

I assume that your vector is sorted (otherwise you could just add new strings to the end).

What are you doing with this vector? Search? In that case you could keep those 15 new strings in another vector, search in that vector first and if not found - search in original one.

Upvotes: 0

Arush Agarampur
Arush Agarampur

Reputation: 1420

std::vector is not designed for frequent addition of elements in the middle, especially if it is very large (one million elements is huge.) Consider using std::list - a double linked list where adding elements in the middle is very fast, because all you have to do is change a few pointers. In std::vector, all the elements have to be moved over, which of course, causes lots of overhead.

But at the same time, accessing single elements in std::list is slow, because you need to traverse the entire list until you find the one you want.

So pick your poison, but I highly suggest using std::list for this case.

Upvotes: 2

Related Questions