简体   繁体   中英

Difference between 2D vector declarations

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.

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).

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 can push_back other vector` and generally manipulate its elements (eg, erase them, insert other elements etc.).

The main difference between a vector and a C-style array is that the vector hasn´ta 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.

@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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM