Thomas Thomas - 1 month ago 5
C++ Question

How can I overwrite an item pointed by the index of a vector?

I would like to overwrite an item pointed by index even if that index doesn't exist yet. operator[] works up until it is not out of bound. emplace seems to do this, but it need an iterator for the first param. I could use myvector.begin()+index but it's invalid when the vector is empty.

Clarification. My current implementation:

while (index < myvector.size())
myvector.push_back("");

myvector[index] = val;


I was hoping for an std method. The array is always very small (few elements).

Using the accepted answer, my code changes to:

if (index < myvector.size()) // to avoid destroying the remaining elements when the index is smaller than current size
myvector.resize(index+1);
myvector[index] = val;

Answer

To overwrite an element of given index, that index must be inside valid vector bounds.

You can set the size of your vector to whatever value using vector::resize, and just use operator[] with indexes in the range [0, size-1]:

std::vector<std::string> data;
...
data.resize(100);
// Use data[i] for i = 0,1,2,...99
Comments