I want to declare a 2D array inside a class. The size of the array will be initialized in the constructor. In Java, I can perform this operation as
public class A { public int[][] indices; A(int a,int b){ indices = new int[a][b]; } }
How can I perform the same operation in C ++?
Use the vector of vectors:
std::vector<std::vector<squares>> squares;
And initialize the constructor:
squares.resize(xPos); for (int i = 0; i < xPos; i++) { squares[i].resize(yPos); }
In C ++, a more popular way for a 2D array is to use a 2D vector. This will have many benefits.
[][]
myVector.push_back(vec)
myVector[i].push_back(x)
, - ArrayList Java.
ArrayList
Java
, ,
#include <vector> public class A { std::vector<std::vector<int>> indices; //... }
, - . . , , . , . uBLAS, . :
uBLAS
int main () { using namespace boost::numeric::ublas; matrix<double> m (3, 3); for (unsigned i = 0; i < m.size1 (); ++ i) for (unsigned j = 0; j < m.size2 (); ++ j) m (i, j) = 3 * i + j; std::cout << m << std::endl; }
, , ++
class C { int** someArray; public: C() { someArray = new int*[ SIZE_GOES_HERE ]; for( unsigned int j = 0; j < SIZE_GOES_HERE; ++j ) someArray[ j ] = new int[ SECOND_SIZE ]; } };
, , , , , , 2d-.
Source: https://habr.com/ru/post/1541897/More articles:Количество уникальных символов в строке в Scala - scalaHow does this function calculate the absolute value of a float using NOT and AND? - c ++Implementing a simple tac - perl programDictionary Types in .Net - collectionsLinux C Standard I / O - why duplication - cGoogle Play Game Services unlocks the achievement - keep the unlock in the game or unlock the call () every time? - javaIs this a good reason for non-polymorphic inheritance? - c ++How can I overcome race conditions in directives without a timeout function? - angularjsAndroid in-app purchase: how to consume? - androidHow to find the path to a font file in Java 7 and 8 - javaAll Articles