c++ - 在 C++ 中的两个 vector 之间交换不同长度的序列

标签 c++ stl vector range swap

假设您有两个整数 vector :

enter image description here

enter image description here

我想定义一个函数,允许我在两个 vector 之间交换一系列元素,传递起始索引和两个序列的长度作为参数。

例如:enter image description here其中 enter image description hereenter image description here是 vector ,作为参数传递的数字表示序列的起始索引和长度。

在这种情况下我应该得到 as autput

v1 = 1,2, 13,14,15 ,5,6,7,8,9

v2 = 10,11,12, 3,4 ,16,17,18

我作为示例定义的函数的签名不是约束,如果你认为有更好的方法就可以

最佳答案

似乎所有常规的 STL 算法都达不到您想要做的事情:

std::swap_ranges 几乎就在那里,但它要求您交换同样长的范围 std::rotate 也不错,但它要求一个范围的终点等于第二个范围的起点。

// pseudo-splice on vector
v1.insert(v1.begin() + 2 + 2, v2.begin() + 3, v2.begin() + 3 + 3);
v2.erase(v2.begin() + 3, v2.begin() + 3 + 3);

// pseudo-splice on vector
v2.insert(v2.begin() + 3, v1.begin() + 2, v1.begin() + 2 + 2);
v1.erase(v1.begin() + 2, v1.begin() + 2 + 2);

您当然可以轻松地将其抽象为一个函数模板,该模板为您的两个范围采用任意迭代器边界。

编辑 根据大卫的评论,你可以做一些优化以避免不必要的调整

// compute smallest range here, in this case it's the v1 part
std::swap_ranges(v1.begin() + 2, v1.begin() + 2 + 2, v2.begin() + 3);

// now handle the remaining part of the longest range, in this case it's element v2 + 3 + 2
std::insert(v1.begin() + 2 + 2, v2.begin() + 3 + 2);
std::erase(v2.begin() + 3 + 2);

更新:如果你使用 std::list 会更容易,因为那时你可以使用 splice(我重新安排了 插入/erase 部分以模仿下面的代码)

v1.splice(v1.begin() + 2 + 2, v2, v2.begin() + 3, v2.begin() + 3 + 3);
v2.splice(v2.begin() + 3, v1, v1.begin() + 2, v1.begin() + 2 + 2);

关于c++ - 在 C++ 中的两个 vector 之间交换不同长度的序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12026924/

相关文章:

c++ - 是否有适用于 OS X 的 Vector3 实现?最好是 Objective-C?

c++ - 警告 "C++ requires a type specifier for all declaration"图

构造函数上的 C++ vector 释放

c++ - 在 Intel Iris Graphics 6100 (MBP 2015) 上实现 OpenCL 的 OSX vector 宽度

c++ - 当我运行书中的演示项目时,Directx 12 说找不到指定的路径

c++ - 使用智能指针进行手动内存管理的最佳策略?

c++ - 使用函数集 c++

c++ - 双向解引用迭代器的返回类型

c++ - std::vector、构造函数、对象

c++ - 可靠地确定 char 的大小