Thomas Thomas - 1 year ago 63
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[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[index] = val;

Answer Source

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;
// Use data[i] for i = 0,1,2,...99
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download