我们可以使用Back() - 值索引在其上执行向量插入
Can we perform insert on a vector using back()-value index on it?
最近,我遇到了一个场景,在该场景中,我必须使用其他向量的切片在向量中插入值并将其放在后面。我尝试使用vector.back() - 值,但它不允许我这样做。这是代码片段
tempVector.insert(inputs.back()-temp,inputs[loopVar]);
,显示的错误为
没有过载函数的实例" std :: vector< _ty,_alloc> :: insert [with _ty = int,_alloc = std ::分配器]"匹配参数列表
我尝试在网上寻找这样的例子,这在此上找不到太多。有人可以告诉我我在这里做错了什么?我是STL和C 14
... 使用其他向量的切片插入向量中的值,然后将其放在后面...
解决方案1:
有一个std::vector::insert()
超负荷具有:
template< class InputIt >
void insert( iterator pos, InputIt first, InputIt last);
因此您可以写:
std::vector<int> a = { 1, 2, 3, 4, 5 };
std::vector<int> b = { 6, 7, 8, 9, 10 };
b.insert(b.end(), a.begin() + 2, a.begin() + 5);
解决方案2:
使用 std::back_insert_iterator
使用std::copy
算法:
std::vector<int> a = { 1, 2, 3, 4, 5 };
std::vector<int> b = { 6, 7, 8, 9, 10 };
std::copy(a.begin() + 2, a.begin() + 5, std::back_inserter(b));
对其进行测试:
for (auto& x : b)
std::cout << x << ' ';
将输出:6 7 8 9 10 3 4 5
insert
方法接受迭代器作为第一个参数(例如,请参见cppReference)。要在背面插入lemt,您可以尝试以下内容:
vec.insert(vec.end(), value);
相关文章:
- 无法在构造函数中执行设置元素插入
- 在 C/C++ 中使用 MySQL 连接器执行插入到表时出错
- 使用 std::stringbuf 进行缓冲的效果,同时通过插入运算符'<<'执行写入
- 插入到映射中的元素在函数执行后清除
- sqlite3 c 函数:插入语句作为参数时未执行
- 插入后执行Houghcircles
- 我们可以使用Back() - 值索引在其上执行向量插入
- 对“呍”数据结构执行插入操作
- 尝试修改 sqlite3 插入以返回 PK。 不确定如何使用 sqlite3 专门执行此操作
- 排序的链表在每次执行时插入重复项
- C++/MySQL,在1次执行中插入200个数据点数组
- QTextEdit插入不一致的HTML(当重复/一致地执行相同的操作时)
- 如何在执行 gdb 时插入断点
- 插入一个“__asm__”块以执行非常大的加法
- 确定插入排序中执行的班次数
- 在可执行文件中插入dll代码,使其不受依赖
- 每次在std::list容器中插入元素时,都会执行动态分配
- 对std::deque执行迭代器在容器两端插入或擦除后会失效
- 关于在链表开头插入节点(程序未正确执行)
- qt QAbstractItemModel 拖放用于移动项目执行删除/插入