Vectors are sequence container which represents Arrays and can change their size during run-time.
Vectors use contiguous blocks of memory (as Arrays) for their elements. That means the elements of the sequence can be accessed using offsets on regular pointers to its elements, as efficiently as arrays. But they can change their size dynamically and the storage is handled by the container.
Vector use dynamically allocated array to store their elements. The feature of using vectors is that, that they can grow in size when new elements are inserted. In case of Arrays if the elements are beyond the range of array's capacity in that scenario we have to declare a new array which can hold all the elements and moving all elements to it, which is very expensive task. Vectors do not reallocate each time an element is added to the container.Instead, vector containers may allocate some extra storage to accommodate for possible growth, and thus the container may have an actual capacity greater than the storage strictly needed to contain its elements (i.e., its size).
A demo program to use vector.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector <int> v; // declaring a vector v which will hold elements of type int
vector <int>:: iterator it; // declaring an iterator it which hold the reference
int tmp;
//inserting elements
for ( int i = 0; i < 10; i++) {
cin >> tmp;
v.push_back(tmp); // inserting the elements into vector v
}
// Used to print all the elements inside the vector
cout << "Output : "
for ( it = v.begin(); it != v.end(); it++) {
cout << *it << " ";
}
cout << endl;
cout << "Elements inside the vector : " << v.size() << endl;
return 0;
}
In the above program we are inserting 10 random integers ( as per your choice) inside the vector.
Let suppose the input be
1 2 3 4 5 5 4 3 2 1
Then the output would be
Output : 1 2 3 4 5 5 4 3 2 1
Elements inside the vector : 10
Some Member Functions of Vector are :
Iterators:
begin
end
rbegin
rend
cbegin
cend
crbegin
crend
Capacity:
size
max_size
resize
capacity
empty
reserve
shrink_to_fit
Element access:
operator[]
at
front
back
data
Modifiers:
assign
push_back
pop_back
insert
erase
swap
clear
emplace
emplace_back
0 Comment(s)