在向量的给定位置(多个)插入一个元素
Inserting an element in given positions (more than one) of a vector
我正在尝试将循环中的某个值添加到某个向量的给定位置。例如:
- 值为 11,因此
local_index = 11
- 我输入的位置向量是
neigh = {5,7}
- 起始向量是
Col={0,1,2,3,4,5,6,7,8,9,10}
我想要输出 Col={0,1,2,3,4,5,11,6,7,11,8,9,10}
。这是我的第一次尝试:
vector<long> neigh = {5,7};
long local_index = 11;
auto pos_col = Col.begin();
for (const auto& elem: neigh) {
Col.insert(pos_col+elem,local_index);
我一直在为 neigh
的第二个值获取分段错误。所以我的问题是:
- 这是因为插入return一个不能重新赋值的指针吗?
- 如果第一个问题的答案是肯定的,我该如何实现我的目标?
根据 cppreference.com 上的 vector::insert()
文档:
Causes reallocation if the new size()
is greater than the old capacity()
. If the new size()
is greater than capacity()
, all iterators and references are invalidated. Otherwise, only the iterators and references before the insertion point remain valid. The past-the-end iterator is also invalidated.
这意味着,在您第一次调用 insert()
后,您的 pos_col
迭代器现在对后续调用 insert()
无效,因为它引用插入点之前的元素.
试试改用这个:
auto pos_col = Col.begin();
for (const auto& elem: neigh) {
Col.insert(pos_col+elem,local_index);
pos_col = Col.begin();
}
或者简单地说:
Col.insert(Col.begin()+elem,local_index);
我正在尝试将循环中的某个值添加到某个向量的给定位置。例如:
- 值为 11,因此
local_index = 11
- 我输入的位置向量是
neigh = {5,7}
- 起始向量是
Col={0,1,2,3,4,5,6,7,8,9,10}
我想要输出 Col={0,1,2,3,4,5,11,6,7,11,8,9,10}
。这是我的第一次尝试:
vector<long> neigh = {5,7};
long local_index = 11;
auto pos_col = Col.begin();
for (const auto& elem: neigh) {
Col.insert(pos_col+elem,local_index);
我一直在为 neigh
的第二个值获取分段错误。所以我的问题是:
- 这是因为插入return一个不能重新赋值的指针吗?
- 如果第一个问题的答案是肯定的,我该如何实现我的目标?
根据 cppreference.com 上的 vector::insert()
文档:
Causes reallocation if the new
size()
is greater than the oldcapacity()
. If the newsize()
is greater thancapacity()
, all iterators and references are invalidated. Otherwise, only the iterators and references before the insertion point remain valid. The past-the-end iterator is also invalidated.
这意味着,在您第一次调用 insert()
后,您的 pos_col
迭代器现在对后续调用 insert()
无效,因为它引用插入点之前的元素.
试试改用这个:
auto pos_col = Col.begin();
for (const auto& elem: neigh) {
Col.insert(pos_col+elem,local_index);
pos_col = Col.begin();
}
或者简单地说:
Col.insert(Col.begin()+elem,local_index);