如何重写由向量索引指向的项?

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

本文关键字:索引 向量 何重写 重写      更新时间:2023-10-16

我想覆盖由索引指向的项,即使该索引还不存在。运算符[]一直工作到不超出边界为止。Emplace似乎可以做到这一点,但它需要第一个参数的迭代器。我可以使用myvector.begin()+index,但是当vector为空时无效。

澄清。我当前的实现:

while (index < myvector.size())
    myvector.push_back("");
myvector[index] = val;

我希望有一个std方法。数组总是非常小(元素很少)。

使用接受的答案,我的代码更改为:

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;

若要覆盖给定索引的元素,则该索引必须在有效的向量边界内。

你可以使用vector::resize设置向量的大小为任何值,并且只使用operator[]的索引范围为[0, size-1]:

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