C++ 从函数返回数组 [英] C++ return array from function

查看:101
本文介绍了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.

这就是我想在概念上做的:

This is what I want to do in concept:

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 代替,或者如果您只有一定数量的元素并且想要表达它(并且确实需要更好的性能),请使用 boost::array.(甚至 std::array,如果你用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].

这篇关于C++ 从函数返回数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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