gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:15:45 25 4
gpt4 key购买 nike

假设您有两个整数 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com