Previously, I've been creating 2D arrays of class Object
using the pointer, in the following syntax:
Object** myArray = new Object*[row_num];
for (int i = 0; i < row_num; i++)
{
myArray[i] = new Object[col_num];
[skip]
}
However, many people have been recommending me to use vector<vector<Object>>
rather than using Object**
.
As far as I'm concerned, vector requires more memories as a trade-off for easier change in the array size. However, since the 2D array that I need is used for a backtracking algorithm of a grid (which would never change its dimension once it's determined), I do not feel the necessity of changing them.
Are there any other advantages of vector
that I'm unaware of?
As @NathanOliver mentioned, you never need to call delete
(often a customized recursive deletion) for multi-dimensional vectors, as the objects inside will be released when they fall out of scope automatically. This can significantly reduce the amount of code you need to write and maintain.
Obviously, if your vectors
contain objects that were allocated with new
or malloc
, you'll need to delete them normally. This is where shared_ptr
s come in but that's another topic.
While there is a slight overhead for each vector, it is far more in line with the C++ paradigm to use them over traditional C-style arrays. If your vector is of a fixed size, you can also use std::array<T, N>
, and avoid a lot of the overhead that having a dynamically sized container brings.
Consistency in language is important. If you're going to be writing C++ using the standard library, you should stick to that as closely as is possible. I've worked at many places that use random hodge-podge of C and C++ mixed together, and it makes reading and understanding the code a nightmare.
There are a few advantages of using vectors over raw arrays. First you don't have to remember to delete
anything as the vector takes care of that when it goes out of scope. Secondly a vector has a lot a built in member functions that mike life easier like size()
and at()
. Third you can use ranged based for loops with them and you can write code like:
// print out all elements in a jagged 2d structure
std::vector<std::vector<int>> data;
// load data into data
for (const auto & row : data)
for (const auto & elem : row)
//print out elem
Which is very clean looking and understandable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With