如何覆盖向量索引指向的项目?
How can I overwrite an item pointed by the index of a vector?
我想覆盖索引指向的项目,即使该索引尚不存在。 operator[] 一直工作,直到它没有超出范围。 emplace 似乎是这样做的,但它需要第一个参数的迭代器。我可以使用 myvector.begin()+index 但是当向量为空时它是无效的。
澄清。我当前的实现:
while (index < myvector.size())
myvector.push_back("");
myvector[index] = val;
我希望有一个标准方法。数组总是很小(元素很少)。
使用已接受的答案,我的代码更改为:
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
我想覆盖索引指向的项目,即使该索引尚不存在。 operator[] 一直工作,直到它没有超出范围。 emplace 似乎是这样做的,但它需要第一个参数的迭代器。我可以使用 myvector.begin()+index 但是当向量为空时它是无效的。
澄清。我当前的实现:
while (index < myvector.size())
myvector.push_back("");
myvector[index] = val;
我希望有一个标准方法。数组总是很小(元素很少)。
使用已接受的答案,我的代码更改为:
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