Dinar Abdullin
Dinar Abdullin

Reputation: 165

Passing 2D array through the class in C++

I would like to create a 2D array of floats, pass it through a certain class, which changes the elements of the array in one of its functions and returns this array back. Importantly, I do not want to create a copy of my array inside the class. What is the best way to do that? I read that people suggest using big 1D array instead of 2D, some people recommend using vectors. That is the most effective (in terms of time) method to do it?

Upvotes: 2

Views: 307

Answers (3)

andre
andre

Reputation: 7249

Here is a 2d array implementation using a single vector. Its a template so you just make a array_2d and everything works as it should.

There are a few advantages to this method:

  • No need to worry about the array decaying into a pointer
  • A 1D vector does not fragment memory like a std::vector<std::vector<float> >
  • Memory management is done for you, so the chances of a memory leak is minimal.

Upvotes: 2

oldmonk
oldmonk

Reputation: 739

 #include <string>
 #include <iterator>
 #include <iostream>
 #include <algorithm>
 #include <array>

 using std::array ;

 array< array<int, 10 > , 20 > a ; //declared 20x10 2 dimension array

Upvotes: 1

taylorc93
taylorc93

Reputation: 3716

Arrays are passed by reference in C++, so if you just pass the array into whatever function you need to change it, then it will keep those changes. No need for anything complicated. Basically just:

type array[num1][num2];
//fill it with values here
yourObject.arrayChanger(array);

Upvotes: 3

Related Questions