c + +从函数返回数组 [英] C++ return array from function
问题描述
我需要在阵列中以我的功能来读取,提取数据,然后从该函数返回一个数组
I need to read in an array to my function, extract the data, and then return an array from the function.
该阵列将只持有2的值。
The array will only ever hold 2 values.
这是我想要的概念做:
int myfunction(int my_array[1])
{
int f_array[1];
f_array[0] = my_array[0];
f_array[1] = my_array[1];
// modify f_array some more
return f_array;
}
我读过上涨约指针等,但都得到了很迷茫,将AP preciate如何最好地处理这个一个非常基本的例子!
I've read up about pointers etc but have got very confused and would appreciate a really basic example of how best to approach this!
谢谢!
推荐答案
您不能在C返回数组内置++。
You can't return an builtin array in c++.
如果您在C ++新弄不清楚你的指针真的不想使用数组(至少不是内置阵列)。使用 的std ::矢量<&INT GT;
代替,或者如果你永远只能拥有一定数量的元素,并希望前preSS的(和真的需要更好的性能)使用的boost ::数组< INT,N方式>
(甚至的std ::阵列< INT,N>
,如果您在编写 C + +11
(如果你不知道你是否没有编写C ++ 11
有机会,你不这样做)。
例如:
If you are new at c++ and get confused about pointers you really don't want to use arrays (at least not builtin arrays). Use std::vector<int>
instead, or if you only ever have a certain number of elements and want to express that (and really need the better performance) use boost::array<int, N>
.(or even std::array<int, N>
, if you program in C++11
(if you don't know whether or not you program in C++11
chances are that you don't).
For example:
std::vector<int> myfunction(const std::vector<int>& my_array) {
std::vector<int> f_array;
for(int i = 0; i < my_array.size(); ++i)
f_array.push_back(my_array[i]);
return f_array;
}
boost::array<int, 2> myfunction(const boost::array<int, 2>& my_array) {
boost::array<int, 2> f_array;
f_array[0] = my_array[0];
f_array[1] = my_array[1];
return f_array;
}
您就可以让你的复印code简单(查找构造函数和你决定使用什么类的memberfunctions,以及STL算法)。例如:
You can then make your copying code simpler (look up the constructors and memberfunctions of whatever class you decide to use, as well as STL algorithms). Example:
std::vector<int> myfunction(const std::vector<int>& my_array) {
std::vector<int> f_array(m_array);
...
return f_array;
}
至于另一点你的code有一个错误在里面:你定义 my_array
为 INT my_array [1]
,这意味着它与一个元素的数组,但您可以访问两个元素( my_array [0]
和 my_array [1]
)之后,获得 my_array [1]
是出界(的 INT富[N]
已到位 N
元素,从指数 0
键,将指数 N-1
)。我假设你真的是 INT my_array [2]
。
As another point your code has a bug in it: you define my_array
as int my_array[1]
, meaning its an array with one element, but you access two elements (my_array[0]
and my_array[1]
), the access to my_array[1]
is out of bounds (int foo[N]
has place for N
items, starting at index 0
and going to index N-1
). I assume you really mean int my_array[2]
.
这篇关于c + +从函数返回数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!