Vectors in C++
are sequence containers representing arrays that can change their size during runtime. They use contiguous storage locations for their elements.
1D Vectors
Syntax
vector<data_type> variable_name
vector<int> vect;
Initializition of vector
Iteration on vector
1
vector<int> vect(n, 10);
for (int x : vect)
cout << x << " ";
2
vector<int> vect(n, 10);
// Traversing the vector using
// values directly
// no need to define datatype of vector
for (auto& it : vect) {
// Print the values
cout << it << ' ';
}
Insert Elements into vector
Access Elements of vector
deleting vector elements
Other functions
Why Vector ?
- Size of arrays are fixed whereas the vectors are resizable i.e they can grow and shrink as vectors are allocated on heap memory. Arrays have to be deallocated explicitly if defined dynamically whereas vectors are automatically de-allocated from heap memory.
- Reserve space can be given for vector, whereas for arrays you cannot give reserved space.
- A vector is a class whereas an array is a datatype.
- Vectors can store any type of objects, whereas an array can store only homogeneous values.
Top comments (0)