What are C ++ dynamic arrays?

, . , , . . , , . , , .

Heap memory allocation




, . . C++ new delete. new (free store heap .). , delete .

, new delete . . , . . .





new . - , (, ) . new : double, char, int . . .

	int *p = new int; // * - ,    .   .
	*p = 9;
	delete p;

      
      



, .

	double *a = new double[10]; // a -   ,     10   double
	a[5] = 2.5;
	delete [] a; //    !  !

      
      



delete , , .

- . …

	double **ma = new double *[5]; // 1
	for(int I = 0; I < 5; i++) // 2
		ma[i] = new double[10];

      
      



, C++ 5 10. 5 . , , 10 , .









Two-dimensional dynamic array




? . . , - , , , .

, ? .

	for(int I = 0; i < 5l i++)
		delete [] ma[i];
	//,  - …
	delete [] ma; 

      
      



.

«»?

, , . :

  1. .
  2. .
  3. .

STL vector –

<vector>.

, (STL) , . . . , , . . – , .

. C++ . . , – , , . , . .

#include <vector>
#include <iostream>
int main() {
	std::vector<int> v; //       int
				//  –   std,  std::
	for(int i = 0; i <= 5; ++i) {
		v.push_back(i);
	}
	for(int i = 0; i < v.size(); ++i) {
		std::cout << v[i] << ", ";
	}
	std::cout << std::endl;
	system("pause");
}

      
      



, , . , ++ .size() .push_back(). , - .

Adding a Vector Element




– , . .

V[index]

V.at(index)

,

V.front()

V.back()

, .at(), out_of_range, try-catch. [] .front() .back() .

++ - 5 5.

Mn matrix diagram




    vector< vector<int> > v(5, vector<int>(5));
    v[2][3] = 10;
    int a = v[2][3];
    v[2].push_back(5); //     
    v[2].pop_back(); //  
      
      



. : , -, . . . . , . .

Deleting a Vector Element




, . STL , . , ( ). .




All Articles