Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between vector <int> V[] and vector< vector<int> > V

Tags:

vector <int> V[] and vector< vector<int> > V both are 2D arrays.

But what is the difference between them and where do we use each one? Please give a brief explanation.

like image 452
Sakib Ahammed Avatar asked Feb 25 '15 06:02

Sakib Ahammed


2 Answers

vector<int> V[] is an array of vectors.

vector< vector<int> > V is a vector of vectors.

Using arrays are C-style coding, using vectors are C++-style coding.

Quoting cplusplus.com ,

Vectors are sequence containers representing arrays that can change in size.

Just like arrays, vectors use contiguous storage locations for their elements, which means that their elements can also be accessed using offsets on regular pointers to its elements, and just as efficiently as in arrays. But unlike arrays, their size can change dynamically, with their storage being handled automatically by the container.

TL;DR:

When you want to work with a fixed number of std::vector elements, you can use vector <int> V[].

When you want to work with a dynamic array of std::vector, you can use vector< vector<int> > V.

like image 88
shauryachats Avatar answered Oct 07 '22 15:10

shauryachats


One difference would be that although both can be initialized in the same way, e.g.

vector<int> V1[]        {{1,2,3}, {4,5,6}}; vector<vector<int>> V2  {{1,2,3}, {4,5,6}}; 

and accessed

cout << V1[0].back() << endl; cout << V2[0].back() << endl; 

the V1 can't grow. You cannot make V1.push_back(...) as its not a vector object. Its just an array. Second one is dynamic. You can grow it as you please.

like image 22
Marcin Avatar answered Oct 07 '22 14:10

Marcin