what is the difference in vector and dynamic array? |
1.
std::vector wraps an array in a C++ class template.
2.
std::vector manages its memory automatically, a programmer doesn't have to use
malloc() or
new to use a vector. When a vector goes out of scope the used memory is automatically released.
3.
std::vector keeps track of the number of elements, the size of the vector.
4.
std::vector is easily resizable at run-time, increasing or decreasing the number of elements as needed using member functions.
5.
std::vector can be created empty, with a specified number of elements or specified number of elements filled with a specified value.
1 2 3 4 5 6 7 8
|
// create an empty vector (zero elements)
std::vector<int> aVector;
// create a sized vector, elements are all zeroes
std::vector<int> aVector2(5);
// create a size vector, with a provided value
std::vector<int> aVector3(5, 10);
|
6.
std::vector provides iterator functions to make sequentially accessing elements less prone to get out of bounds errors.
1 2 3 4 5
|
for (auto itr = aVector2.begin(); itr != aVector2.end(); itr++)
{
std::cout << *itr << ' ';
}
std::cout << '\n';
|
7.
std::vector works well with
range-based for loops
1 2 3 4 5
|
for (auto itr : aVector3)
{
std::cout << itr << ' ';
}
std::cout << '\n';
|
8.
std::vector allows elements to be inserted and erased at any position in the vector.
9. Since
std::vector keeps track of its size, having a vector as a function parameter doesn't require an additional parameter of the vector's size.
1 2
|
foo(aVector);
foo(anArray[ ], size);
|