如何将函数的返回保存到另一个数组? [英] How can save the return of a function to another array?
问题描述
我写了一个返回数组的函数;那么如何将返回的数组保存(复制)到另一个数组中。什么是最好最快的方式?
I wrote a function which returns an array; so how can I save (copy) that returned array into another array. What is the best and fastest way?
//function declaration
int func (int array[]);
// function defenition
int func (int array[]){
....
return result[];
}
推荐答案
不是通过在这里发布问题来尝试学习C ++,而是花费更多时间掌握一本关于这个主题的好书并完成它。看看这个以及你发布的另一个问题,似乎缺乏对一些基础知识的理解。
Rather than trying to learn C++ by posting questions here, your time would really be better spent getting hold of a good book on the subject and working through it. Looking at this and the other question you posted, there seems to be a lack of understanding of some of the basics.
你的函数应该这样声明
You function should be declared this way
int * func(int array[]);
请注意:您应该返回 static
数组或动态分配(例如使用 new
)。后一种技术要求调用者删除数组以防止内存泄漏。
Please note: you should either return a static
array or a dynamically allocated (e.g. using new
) one. The latter technique requires the caller to delete the array in order to prevent memory leaks.
示例代码:
#include <iostream>
int * func(int array[])
{
//...
static int b[]={1,2,3};
return b;
}
//
int main()
{
int a[] = {4,5,6};
int * p = func(a);
std::cout << p[2] << std::endl;
}
这样的代码容易出错,这是值得的,它可能更好用 std :: vector
代替。
[更新]
这里你是 C
-like version
It is worth nothing such code is prone to errors, it's probably better using std::vector
instead.
[update]
Here you are a C
-like version
#include <iostream>
using namespace std;
void dump(int * x, int lx);
void pad(int * d, int ld, int *s, int ls);
int main()
{
int a[] = {1,2,3};
int b[] = {4,6,8,10,12};
// length of a and b
int la = sizeof(a)/sizeof(a[0]);
int lb = sizeof(b)/sizeof(b[0]);
int lp = 0;
int * p = NULL;
if ( la > lb)
{
lp = la;
p = new int[lp];
pad(p, lp, b, lb);
}
else if (la < lb)
{
lp = lb;
p = new int[lp];
pad(p, lp, a, la);
}
dump(a, la);
dump(b, lb);
dump(p, lp);
if ( p ) delete [] p;
}
void dump(int * x, int lx)
{
for (int n=0; n<lx; ++n) cout << x[n] << " ";
cout << endl;
}
void pad(int * d, int ld, int *s, int ls)
{
int n;
for (n=0; n<(ld-ls); ++n)
d[n] = -1;
for ( ;n<ld;++n)
d[n] = s[n-ld+ls];
}
[/ update]
[更新2]
更类似于 C ++
(你需要一个现代的编译器)
[/update]
[update 2]
More similar to C++
(you need a modern compiler)
#include <iostream>
#include <vector>
using namespace std;
void dump( vector<int> v );
int main()
{
vector <int> a{1,2,3};
vector <int> b{4,6,8,10,12};
vector <int> p;
if ( a.size() > b.size())
{
p.insert(p.end(), a.size()-b.size(),-1);
p.insert(p.end(), b.begin(), b.end());
}
else if (a.size() < b.size())
{
p.insert(p.end(), b.size()-a.size(), -1);
p.insert(p.end(),a.begin(), a.end());
}
dump(a);
dump(b);
dump(p);
}
void dump( vector<int> v )
{
for (auto x : v)
cout << x << " ";
cout << endl;
}
[/ update2]
[/update2]
这篇关于如何将函数的返回保存到另一个数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!