Isn't it a waste of time to initialize a vector with zeros, when you don't want it?
I try this code:
#include <iostream>
#include <vector>
#include <array>
#define SIZE 10
int main()
{
#ifdef VECTOR
std::vector<unsigned> arr(SIZE);
#else
std::array<unsigned, SIZE> arr;
#endif // VECTOR
for (unsigned n : arr)
printf("%i ", n);
printf("\n");
return 0;
}
and I get the output:
with vector
$ g++ -std=c++11 -D VECTOR test.cpp -o test && ./test
0 0 0 0 0 0 0 0 0 0
with an array
g++ -std=c++11 test.cpp -o test && ./test
-129655920 32766 4196167 0 2 0 4196349 0 1136 0
And I also try with clang++
So why zeros? And by the way, could I declare a vector without initializing it?
Difference between std::vector and std::array in C++Vector is a sequential container to store elements and not index based. Array stores a fixed-size sequential collection of elements of the same type and it is index based. Vector is dynamic in nature so, size increases with insertion of elements.
Vector are implemented as dynamic arrays with list interface whereas arrays can be implemented as statically or dynamically with primitive data type interface. Size of arrays are fixed whereas the vectors are resizable i.e they can grow and shrink as vectors are allocated on heap memory.
std::array contains a built-in array, which can be initialized via an initializer list, which is what the inner set is. The outer set is for aggregate initialization.
You can initialize a vector by using an array that has been already defined. You need to pass the elements of the array to the iterator constructor of the vector class. The array of size n is passed to the iterator constructor of the vector class.
The more common way to declare a vector is without specifying the size:
std::vector<unsigned> arr;
This doesn't allocate any space for the vector contents, and doesn't have any initialization overhead. Elements are usually added dynamically with methods like .push_back()
. If you want to allocate memory you can use reserve()
:
arr.reserve(SIZE);
This doesn't initialize the added elements, they're not included in the size()
of the vector, and trying to read them is undefined behavior. Compare this with
arr.resize(SIZE);
which grows the vector and initializes all the new elements.
std::array
, on the other hand, always allocates the memory. It implements most of the same behaviors as C-style arrays, except for the automatic decay to a pointer. This includes not initializing the elements by default.
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