简体   繁体   中英

how to pass two dimensional array as parameter in a function and return a two dimensional array in c++?

In C++, how to pass two dimensional array as parameter in a function and this function returns a two dimensional array?

if I have a array defined like this:

struct Hello
{
   int a;
   int b;
};

Hello hello[3][3] = {.......};

how to return the array above in a function?

The answer depends on what you mean by a two-dimensional array.

The C++ way would be to have a std::vector<std::vector<Type> > , in which case the answer is like this

typedef std::vector<std::vector<myType> > Array2D;

Array2D f(const Array2D& myArray)
{

}

If you've allocated your array dynamically in Type** as in

Type** p  = new Type*(n);
for(int i = 0; i < n; ++i)
{
    p[i] = new Type(m);
}

then you can simply pass the Type** along with the dimensions.

... f(Type** matrix, int n, int m);

If you have a normal 2D array as

 Type matrix[N][M];

then you can pass it as

template<int N, int M>
... f(Type (&matrix)[N][M]);

I have deliberately left the return type in the two previous examples blank because it depends on what are you returning (the passed array or a newly created one) and the ownership policy.

Hello(&f(Hello(&In)[3][3])) [3][3] {
    //operations
    return In; 
} 

Hardly readable (typedef is recommended), but you can do it:

Hello(&f(Hello(&A)[3][3])) [3][3] {
    // do something with A
    return A; 
} 

You actually do not need to return if this is the same array. Return void instead - syntax will be much simpler.

I'd do it like this...

typedef std::vector< int > vectorOfInts;
typedef std::vector< vectorOfInts > vectorOfVectors;

vectorOfVectors g( const vectorOfVectors & voi ) {
  std::for_each( voi.begin(), voi.end(), [](const vectorOfInts &vi) {
    std::cout<<"Size: " << vi.size() << std::endl;
    std::for_each( vi.begin(), vi.end(), [](const int &i) {
      std::cout<<i<<std::endl;
    } );
   } );

  vectorOfVectors arr;
  return arr;
}

int main()
{
  vectorOfVectors arr( 10 );
  arr[0].push_back( 1 );
  arr[1].push_back( 2 );
  arr[1].push_back( 2 );
  arr[3].push_back( 3 );
  arr[3].push_back( 3 );
  arr[3].push_back( 3 );
  g( arr );
  return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM