Declare, Initialize and Access a Vector | C++ STL

In this article, we will learn how to declare a vector in C++ STL (Standard Template Library), how to initialize it and how to access a vector in C++ STL?
Submitted by IncludeHelp, on August 24, 2018

Here, we have to declare, initialize and access a vector in C++ STL.

Vector declaration

Syntax:

 vector<data_type> vector_name;

Since, vector is just like dynamic array, when we insert elements in it, it automatically resize itself.

We can also use, the following syntax to declare dynamic vector i.e a vector without initialization,

vector<data_type> vector_name{};

If, we want to initialize a vector with initial elements, we can use following syntax,

vector<data_type> vetor_name{elements};

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;

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.

Program 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 

Program 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 

Related Tutorials



Comments and Discussions!










Copyright © 2023 www.includehelp.com. All rights reserved.