将一个向量插入另一个向量的某个位置
Inserting a vector in a certain position in another vector
我想在向量a
的某个位置插入向量b
。例如
std::vector <int> vecta{ 10, 20, 30 ,40 , 50};
std::vector <int> vectb{ 1000, 2000, 3000 };
我怎样才能有一个结果向量像{10,20,1000,2000,3000,40,50}? 我想删除30
并将其替换为矢量。
我想在
矢量
a
的某个位置插入矢量b
您可能需要考虑std::vector::insert()
:
vecta.insert(pos, vectb.begin(), vectb.end());
其中pos
上面是一个迭代器,指向元素(vecta
(之前插入vectb
的内容。pos
也可能是end()
返回的迭代器,这意味着将vectb
的内容附加到vecta
。
我怎样才能有一个结果向量像{10,20,1000,2000,3000,40,50}
为此,您还需要从vecta
中删除元素30
。您可以使用std::vector::erase()
执行此操作:
auto main() -> int {
std::vector <int> vecta{ 10, 20, 30, 40 , 50};
/* ^
|-- insert vectb here and replace the 30
*/
std::vector <int> vectb{ 1000, 2000, 3000 };
// what element to erase from vecta?
auto pos = vecta.begin() + 2;
// erase it
pos = vecta.erase(pos);
// insert vectb in vecta
vecta.insert(pos, vectb.begin(), vectb.end());
for (auto& e: vecta)
std::cout << e << " ";
std::cout << std::endl;
}
std::vector::erase()
返回已删除元素后面的迭代器。由于您要从vecta
中删除30
,然后在该位置插入vectb
,因此您只需将迭代器erase()
返回到insert()
即可。
您可以使用erase
擦除某个迭代器位置的元素,insert
在某个迭代器位置之前插入元素。要单步执行迭代器,请使用std::next
和std::prev
。
#include <iostream>
#include <iterator>
#include <vector>
int main() {
std::vector<int> vecta{10, 20, 30, 40, 50};
std::vector<int> vectb{1000, 2000, 3000};
// erase 30 from the vector
vecta.erase(std::next(vecta.begin(), 2));
// insert vectb before position 2
vecta.insert(std::next(vecta.begin(), 2), vectb.begin(), vectb.end());
for(int v : vecta) {
std::cout << v << ' ';
}
std::cout << 'n';
}
输出:
10 20 1000 2000 3000 40 50
不需要erase
的替代方案。这可能稍微快一些:
#include <utility> // added for std::swap
int main() {
std::vector<int> vecta{10, 20, 30, 40, 50};
std::vector<int> vectb{1000, 2000, 3000};
std::vector<int> result;
// reserve space for the number of elements you know will be in the resulting vector
result.reserve(vecta.size() - 1 + vectb.size());
// append the 2 first elements from vecta
result.insert(result.end(), vecta.begin(), std::next(vecta.begin(), 2));
// append vectb
result.insert(result.end(), vectb.begin(), vectb.end());
// append the last two elements from vecta
result.insert(result.end(), std::prev(vecta.end(), 2), vecta.end());
// let vecta take over the data in result and vice-a-versa
std::swap(result, vecta);
}
您可以使用vector::insert
现场样品
vecta.erase(vecta.begin() + 2); //<-- erase 30 element
vecta.insert(vecta.begin() + 2, vectb.begin(), vectb.end());
vecta.begin() + 2
vecta
中插入vectb
的点,并vectb.begin(), vectb.end()
您需要插入的vectb
元素的跨度,在这种情况下,所有这些元素。
相关文章:
- 将值指定给向量(2D)的向量中的某个位置
- 使用迭代器时如何访问对象在向量中的位置?
- 如何将元素添加到向量的字符串位置
- 将一个向量插入另一个向量的某个位置
- 向量的内存位置不连续
- 创建一个类来访问和指定向量类型,并构建一个获取位置并为其分配区域的类
- 如何从字符串向量中选择第 n 个位置?
- 在多维向量中的特定位置添加一个值
- 如果不初始化结构中的向量,它会自动为空还是具有随机内存位置的值?
- 如何在向量中保存位置以供以后插入?
- 查找 2D 向量的位置,该向量是类C++的一个元素
- 使用向量的函数崩溃,调试器说访问冲突读取位置
- 如何使用向量 c++ 迭代文件中单词的位置
- 在 c++ 中检查 if 条件中的向量位置范围
- 这是查找向量中元素位置的合法方法吗?
- 如何在C 2D向量中找到对象(而不是int)的位置
- C 从特定位置插入其他向量中的载体
- 向量如何在特定位置调用复制构造函数
- 如何在特定位置不大的推动_back向量
- 嵌套的向量迭代忽略外部向量位置