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?
Asked
Active
Viewed 302 times
2
-
what do you mean by "..which changes the columns of the array in..." ? – andrea.marangoni Jul 12 '13 at 13:18
-
Are looking for [In-place matrix transposition](http://en.wikipedia.org/wiki/In-place_matrix_transposition)? – jrok Jul 12 '13 at 13:18
3 Answers
3
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);
2
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.
-
Thank you andre, I like this way! I recommend everybody to look through this [link](http://stackoverflow.com/questions/2216017/dynamical-two-dimension-array-according-to-input/2216055#2216055) – Dinar Abdullin Jul 12 '13 at 14:22
-
I think this topic is also interesting: [2d array representation](http://stackoverflow.com/questions/1946830/multidimensional-variable-size-array-in-c) – Dinar Abdullin Jul 13 '13 at 20:49
1
#include <string>
#include <iterator>
#include <iostream>
#include <algorithm>
#include <array>
using std::array ;
array< array<int, 10 > , 20 > a ; //declared 20x10 2 dimension array

oldmonk
- 739
- 4
- 10