如何重写由向量索引指向的项?
How can I overwrite an item pointed by the index of a vector?
我想覆盖由索引指向的项,即使该索引还不存在。运算符[]一直工作到不超出边界为止。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
相关文章:
- 在C++中调整向量中的索引
- 给定一个向量,如何找到该向量的所有子集和的原始索引
- 将转换字符键入 int 以用作向量C++的索引
- 在对向量中查找元素的索引
- 如何检查类实例向量的索引是否为空
- 如何根据排序索引的向量对 std::index 集进行排序?
- C++ 中字符串向量的索引
- 如何在C++中返回向量的从零开始的索引
- 向量索引变量声明(size_t 或 std::vector<DATATYPE>::size_type)
- 特征获取索引数组,其中向量中的值为真(不需要循环)
- 引用向量中的特定索引
- 在C++中从距离矩阵创建索引向量的最快方法
- 在python gdb脚本中索引c ++向量
- 使用索引向量擦除另一个向量的索引
- 根据索引向量对向量重新排序 - 更新
- C++11将智能指针的索引向量作为类的成员
- 使用auto关键字填充双索引向量
- C++对不带lambda的索引向量进行排序
- 如何从Eigen中的索引向量中提取子向量(Eigen::Vector)
- 通过索引向量对犰狳矩阵的所有列进行排序的最佳方法