C++从函数返回数组

2022-01-19 00:00:00 function return arrays c++

我需要将一个数组读入我的函数,提取数据,然后从函数返回一个数组.

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;
}

我已经阅读了有关指针等的信息,但非常困惑,希望能有一个非常基本的例子来说明如何最好地解决这个问题!

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++中返回n个内置数组.

You can't return n builtin array in c++.

如果您是 C++ 新手并且对指针感到困惑,那么您真的不想使用数组(至少不是内置数组).请改用 std::vector<int>,或者如果您只有一定数量的元素并且想要表达(并且确实需要更好的性能),请使用 boost::array<int, N>.(甚至是 std::array<int, N>,如果你用 C++11 编程(如果你不知道你是否用 C++11 编程代码>很可能你没有).例如:

If you are new to 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;
}

然后您可以使您的复制代码更简单(查找您决定使用的任何类的构造函数和成员函数,以及 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;
}

另外一点,您的代码中有一个错误:您将 my_array 定义为 int my_array[1],这意味着它是一个包含一个元素的数组,但您可以访问两个元素(my_array[0]my_array[1]),对 my_array[1] 的访问超出范围(intfoo[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].

相关文章