Home »
C++ STL
Declare, Initialize and Access a Vector | C++ STL
By IncludeHelp Last updated : December 11, 2023
Here, we have to declare, initialize and access a vector in C++ STL.
C++ Vector Declaration
Below is the syntax to declare a vector:
vector<data_type> vector_name;
Since, vector is just like dynamic array, when we insert elements in it, it automatically resize itself.
Dynamic Declaration of C++ Vector
We can also use, the following syntax to declare dynamic vector i.e a vector without initialization,
vector<data_type> vector_name{};
C++ Vector Initialization
If, we want to initialize a vector with initial elements, we can use following syntax,
vector<data_type> vetor_name{elements};
C++ Vector Iterator
To access/iterate elements of a vector, we need an iterator for vector like containers. We can use following syntax to declare a vector iterator:
vector<data_type>::iterator iterator_name;
Example:
vector<int>::iterator it;
C++ vector:: begin() and vector::end() functions
Function vector::begin() return an iterator, which points to the first element in the vector and the function vector::end() returns an iterator, which points to the last element in the vector.
Example 1
Declare vector with Initialization and print the elements
#include <iostream>
#include <vector>
using namespace std;
int main() {
// declare vector with 5 elements
vector<int> num{10, 20, 30, 40, 50} ;
//print the elements - to iterate the elements,
//we need an iterator
vector<int>::iterator it;
//iterate and print the elements
cout<< "vector (num) elements: ";
for( it=num.begin(); it!=num.end() ; it++ )
cout<< *it << " ";
return 0;
}
Output
vector (num) elements: 10 20 30 40 50
Example 2
Declare a vector without initialization, insert some elements and print.
To insert elements in vector, we use vector::push_back() – this is a predefined function, it insert/pushes the elements at the end of the vector.
#include <iostream>
#include <vector>
using namespace std;
int main() {
// declare vector
vector<int> num{};
//insert elements
num.push_back (100);
num.push_back (200);
num.push_back (300);
num.push_back (400);
num.push_back (500);
//print the elements - to iterate the elements,
//we need an iterator
vector<int>::iterator it;
//iterate and print the elements
cout<< "vector (num) elements: ";
for(it=num.begin (); it !=num.end (); it++ )
cout<< *it << " ";
return 0;
}
Output
vector (num) elements: 100 200 300 400 500