gpt4 book ai didi

c++ - 交换 N 个变量

转载 作者:行者123 更新时间:2023-11-30 02:13:41 25 4
gpt4 key购买 nike

C++中有函数可以循环改变N个变量的值吗?

例如,我有三个变量:

int i = 5;
int j = 7;
int h = 3;
swap(i,j,h);
// i value is 7
// j value is 3
// h value is 5

我可以使用 N-1 次调用交换函数来实现。但是,它可以以更好的方式实现,执行更少的操作:

int aux = i;
i = j;
j = h;
h = aux;

我对 N 个变量(3、4、5、6、...)感兴趣;

编辑:真的,我有一个 int[],我需要旋转一些元素。

int a[10] = {1,4,5,3,2,7,8,9,6,0};

首先,我计算要旋转的索引集(例如 2、7、5 和 3),然后我需要旋转索引 2、7、5 和 3 处的元素(值 5、9、7、3) ,并产生以下变化:

 0 1 2 3 4 5 6 7 8 9   // indexes
{1,4,5,3,2,7,8,9,6,0}; // values

0 1 7 2 4 3 6 5 8 9 // moved from index
{1,4,9,5,2,3,8,7,6,0}; // new value

最佳答案

您可以按照评论中的建议使用 std::rotate

#include <vector>
#include <array>
#include <algorithm>

template <typename Container>
void rotate_left(Container& c)
{
std::rotate(c.begin(), c.begin() + 1, c.end());
}

int main()
{
int i = 5, j = 7, h = 3;
std::array<int,3> a {i, j, h};
std::vector<int> v {i, j, h};
rotate_left(a);
rotate_left(v);

return 0;
}

EDIT: Really, I have an int[], and I need to rotate some elements.

要回答你的第二个问题,你只需交换值:

#include <vector>

int main()
{
// input taken from your example
std::vector<int> v {1, 4, 5, 3, 2, 7, 8, 9, 6, 0};
std::vector<size_t> indexes {2, 7, 5, 3};

// swap the values by index (7->2, 5->7, 3->5)
// note that 2->3 naturally satisfies, hence ind<indexes.size()-1
for (size_t ind = 0; ind<indexes.size()-1; ++ind)
{
std::swap(v[indexes[ind]],v[indexes[ind+1]]);
}

return 0;
}
// output: 1, 4, 9, 5, 2, 3, 8, 7, 6, 0

这当然也适用于数组 (int[])。确保您的索引不超过 v 的大小。

编辑

来自您的评论:

I am looking for a function that performs the for() {swap} more efficiently

我认为您不会在标准中找到特定内容。但也许这就是您正在寻找的:

#include <vector>

int main()
{
// input taken from your example
std::vector<int> v {1, 4, 5, 3, 2, 7, 8, 9, 6, 0};
std::vector<size_t> indexes {2, 7, 5, 3};

// rotate the values by index (7->2, 5->7, 3->5, 2->3)
int tmp = v[indexes[0]];
for (size_t ind = 0; ind<indexes.size()-1; ++ind)
v[indexes[ind]] = v[indexes[ind+1]];
v[indexes.back()] = tmp;

return 0;
}
// output: 1, 4, 9, 5, 2, 3, 8, 7, 6, 0

Here是您可以使用的基准。

关于c++ - 交换 N 个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58956541/

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