C ++ - How are multidimensional vectors stored?

I have two questions regarding vectors.

  • Let's say I have a multidimensional vector as follows: -

    vector< vector<int> > A;

    Then A[0], A[1]etc. are vectors. How are vectors stored in A? I mean what information about vectors A[0]and A[1]is stored in A? And the reallocation of the memory of individual vectors, such as A[2]  causing redistribution A?

  • Secondly, I tried to see how the vector addresses change during redistribution. I used the following code: -

Code:

vector<int> A;
int* x ;
int* y ;

vector<int>* ad;
vector<int>* bd;

for(int i = 0 ; i < 10000; i++){

    A.push_back(i);
    if(i == 2){
        y = &A[0];
        ad = &A;
    }
    x = &A[0];
    bd = &A;    

}

, A , A[0]. , , new delete. , ( ) &A ( &A ). , .

, .

+4
3

( ) &A

, , - .

, :

  • - [],
  • , , , ,
  • , - , push_back, size().

, . , .

+4

: A , , A , , , (, ). , (ad, bd ) , A (x y, , ). , - .

, A[0] , . A.operator[]; .

, &A: . vector ++. , , - std::vector cppreference.com. , , , , , . , , , , , sizeof().

+2

++ STL, ; -, :

std::vector<int> tmp;
std::cout << sizeof(tmp) << " " << tmp.size() << " " << tmp.capacity << std::endl;

:

12 0 0

for(int i = 0; i != 10; ++i) tmp.push_back(i);
std::cout << sizeof(tmp) << " " << tmp.size() << " " << tmp.capacity << std::endl;

12 10 16

then we can conclude that the vector just holds the pointer, so the result of sizeof () has not changed. So, the answer to your question: the child vector push_back will not lead to the redistribution of the parent vector (I do not know how to express the role of these two vectors). There are some simple codes:

std::vector<int> v1(10);
std::vector<int> v2(10);

int i;
for(i = 0; i != 10; ++i)
    v1[i] = i;
for(i = 0; i != 10; ++i)
    v2[i] = i;

vv.push_back(v1);
vv.push_back(v2);

std::cout << "v1 capacity: " << v1.capacity() << "  v1 size: " << v1.size() << std::endl;
std::cout << "v2 capacity: " << v2.capacity() << "  v2 size: " << v2.size() << std::endl;
std::cout << "vv capacity: " << vv.capacity() << "  vv size: " << vv.size() << std::endl;

for(i = 10; i != 20; ++i)
    v1.push_back(i);
for(i = 10; i != 20; ++i)
    v2.push_back(i);

std::cout << "v1 capacity: " << v1.capacity() << "  v1 size: " << v1.size() << std::endl;
std::cout << "v2 capacity: " << v2.capacity() << "  v2 size: " << v2.size() << std::endl;
std::cout << "vv capacity: " << vv.capacity() << "  vv size: " << vv.size() << std::endl;

exit:

v1 capacity: 10  v1 size: 10
v2 capacity: 10  v2 size: 10
vv capacity: 2  vv size: 2
v1 capacity: 20  v1 size: 20
v2 capacity: 20  v2 size: 20
vv capacity: 2  vv size: 2
0
source

Source: https://habr.com/ru/post/1608214/


All Articles