这是我用 Java 完成的一些事情,但我很难用 C++ 弄明白。
基本上,我有两个数组,我想将第二个数组的内容复制到第一个数组中。与其将时间浪费在将每个数组元素的内容从第二个数组一次复制到第一个的循环中,不如让我的第一个数组变量指向第二个数组的存储位置。
这是一个例子:
void modify(int[]);
int main (){
// foo points to (for example) memory location 123
int foo[5] = { 16, 2, 77, 40, 12071 };
modify(foo);
// foo now contains the modified data
return 0;
}
void modify(int bar[]){
// bar points to memory location 123
// (ie, bar points to the same location as foo)
// baz points to (for example) memory location 4567
int baz[5];
// this loop can't modify my data in-place,
// so it uses baz temporarily
for(int i = 0; i < 5; i++){
int j;
if(i == 0) j = 4;
else j = i - 1;
baz[i] = bar[i] + bar[j];
}
// baz now contains the modified data
// now, I would like to put the data located in 4567 (baz) into foo
// I know I could loop through each element one at a time like:
// for(int i; i < 5; i++)
// bar[i] = baz[i];
// but I feel that for large arrays, this could be unnecessarily slow
// it would be more efficient to say:
// "ok, now foo points to memory location 4567"
// but I don't know how to say that in C++
bar = baz; // this doesn't work :-(
foo = baz; // neither does this :'(
}
我如何在 C++ 中执行此操作?
-- 布莱恩
最佳答案
使用 std::vector
。
您可以使用它的swap
成员函数,但这仅对于通过引用(或指针)传递参数的 C 风格代码是必需的。
而是简单地返回本地创建的结果 vector ,其缓冲区将自动移动到函数结果中。
#include <vector>
using namespace std;
auto modified( vector<int> const& v )
-> vector<int>
{
int const n = v.size();
vector<int> result( n );
for( int i = 0; i < n; ++i )
{
int const j = (i == 0? n - 1 : i - 1);
result[i] = v[i] + v[j];
}
return result;
}
auto main()
-> int
{
vector<int> const foo = { 16, 2, 77, 40, 12071 };
vector<int> const baz = modified( foo );
}
这在某种程度上很像 cooking 。
您干预的越少,您让编译器完成它的工作的次数越多,通常效果会更好,工作量也会更少。
关于c++ - 如何使数组变量指向不同的数组,有效地将第二个数组的内容复制到第一个数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25983186/