C++从函数,指针返回多维数组的最佳方法?

Jac*_*row 1 c++ arrays pointers function

我需要从函数返回一个类对象数组.我从研究中了解到,最好的方法是使用指针,但这是我的程序设计的最佳方法,还需要从多个CPP文件中访问它?

main.cpp中

#include <class.h>
#include <functions.h>

int main(){
Class Object[2][]; //define second dimension here?
some_function(); //should return / create the array with filled in elements.
int var = arr[2][3]; // want to be able to do something like this in main
}
Run Code Online (Sandbox Code Playgroud)

functions.cpp

void some_function(){
// assign values
arr[2][3] = 1;
}
Run Code Online (Sandbox Code Playgroud)

Ton*_*ion 8

你应该真的std::vector<std::vector<Object> >用于你的多维数组.使用原始数组是容易出错的,因为无论如何你都在使用C++,为什么不使用像std::vector需要时自动调整大小的东西.

您甚至可以vector像这样从函数返回:

std::vector<std::vector<Object> > my_function() { /* do something */ return some_vector; }

  • 如果您使用的是C++ 11且Object是可移动的,那么这也是最佳的(因为您不会复制向量中的所有内容).如果您不使用C++ 11,可以将对象放入boost或tr1 shared_ptr. (4认同)