0

It might sound quite simple question but I am a bit confused.What I want to know is difference between these two vector declarations in c++.

vector<  vector<int> >a(some_size)

vector<int>b[some_size]

I want to know situations in which we can use one of these but not other one. Please provide situations other than those dependent on fixed size of array and variable size of vector.Please provide sample code to prove your point.

Thanks in advance.

ComicSansMS
  • 51,484
  • 14
  • 155
  • 166
charany1
  • 871
  • 2
  • 12
  • 27

4 Answers4

5

The second is an array of vectors. The size of the array has to be known at compile time. The first is a vector of vectors. The size can change at runtime.

If you try to look for commonality you could say that both are ranges with the same value_type and category (RandomAccessIterator).

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
pmr
  • 58,701
  • 10
  • 113
  • 156
1

My point is that both of these can be understood as vector of vectors.

Absolutely not: vector<vector<int>>a(some_size) is a vector of vectors. vector<int>b[some_size] is an array of vectors.

Main difference is vector<int>b[some_size] is fixed sized, vector<vector<int>>a(some_size) is dynamic, meaning you canpush_backothervector` and generally manipulate its elements (e.g., erase them, insert other elements etc.).

101010
  • 41,839
  • 11
  • 94
  • 168
  • ok this is right,can you please provide me with some practical use where one is preferred over other! – charany1 Jul 11 '14 at 21:08
  • @charany1 depends on what you want. If you want fixed sized use the second or even better use a `std::array, some_size>`. If you want insertion and deletion on demand use the first. If there a performance gain in using the one over the other is debatable. – 101010 Jul 11 '14 at 21:12
0

The main difference between a vector and a C-style array is that the vector hasn´t a fixed size (ie. can be resized). Something similar can be achieved ith C pointers too, but more complicated, and you need to keep the size epartely etc.etc.

Your first code line creates "some_size" vectors of ints.
Each of this int-vectors can have an own size (different from others)
and you can add/remove whole vectors too.

The second line won´t let you add/remove vectors.

deviantfan
  • 11,268
  • 3
  • 32
  • 49
0

@pmr, @40two, and @deviantfan are right. The first is a vector, with vectors as elements. The second is a c-style array of vectors.

I think the best way to think of this is just to look at the differences between arrays and vectors, which is nicely addressed in this question: Arrays vs Vectors: Introductory Similarities and Differences

Your decision to use one over the other will be whether you need the functionality of a full vector object, or if you can safely perform all the same processes using a simple c-style array.

Community
  • 1
  • 1
CrepeGoat
  • 2,315
  • 20
  • 24