是否可以交换结构数组(在线性时间内)? [英] Is it possible to swap arrays of structs (in linear time)?

查看:82
本文介绍了是否可以交换结构数组(在线性时间内)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小程序,可以计算行星彼此的作用力.我的程序有两个结构数组,一个数组在迭代之前保存位置和速度,另一个数组在迭代之后保存它们的位置和速度.

I have a small program computing the forces of planets on each other. My program has two arrays of structs, one that holds the positions and velocities before iterations, and the other holds what their positions and velocities will be after the iterations.

在每次迭代结束时,我想将值从第二个数组移到第一个数组中,而第二个数组可能会变成垃圾(但需要指向一些我以后可以写的有效内存位置).我以为我可以切换数组,因为数组是指针,但是编译器不允许我这样做.

At the end of each iteration, I'd like to move the values from the second array into the first and the second array can become garbage (but needs to point to some valid memory location I can write to later). I thought I could simply switch the arrays since an array is a pointer, but the compiler won't let me.

请考虑以下示例:

typedef struct { int a; } Foo;

int main()
{
   Foo bar[8], baz[8];

   Foo *temp = baz;
   baz = bar;   //ISO C++ forbids the assignment of arrays
   bar = temp;  //incompatible types in assignment of Foo* to Foo[8]
}

这就是我想要做的.当然,这比从1到N的for循环要快.

This is what I'd like to do. It would certainly be faster than a for loop from 1 to N.

推荐答案

您应该考虑使用std::vector,它可以在恒定时间内交换:

You should consider using std::vector which can be swapped in constant time:

std::vector<Foo> bar(8), baz(8);

std::swap(bar, baz);

或者如果您不想这样做,而是想手动管理您的内存,则可以使用new[]来获取指向免费存储中的数组的指针,并在想要交换数组时交换指针

Or if you don't want to do that and instead want to manually manage your memory, you can use new[] to get a pointer to an array on the free store and swap the pointers when you want to swap the arrays.

如果必须在堆栈上放置数组,则在不实际交换每个元素的情况下执行此操作的唯一方法是在堆栈上创建数组,而不是使用数组,而应使用指向数组的指针:

If you must have your arrays on the stack, the only way to do this without actually swapping each element would be to create the arrays on the stack and instead of using the arrays, use pointers to the arrays:

Foo bar[8], baz[8], *pbar = bar, *pbaz = baz;

// ...
// this code only using pbar and pbaz
// ...

// swap the pointers
std::swap(pbar, pbaz);

// ...
// use pbar and pbaz some more
// ...

这篇关于是否可以交换结构数组(在线性时间内)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆