vector::begin() and vector::end() in C++ STL

C++Server Side ProgrammingProgramming

vector::begin() function is a bidirectional iterator used to return an iterator pointing to the first element of the container.

vector::end() function is a bidirectional iterator used to return an iterator pointing to the last element of the container.

Algorithm

Begin
   Initialize the vector v.
   Declare the vector v1 and iterator it to the vector.
   Insert the elements of the vector.
   Print the elements.
End.

Example Code

 Live Demo

#include<iostream>
#include <bits/stdc++.h>
using namespace std;

int main() {
   vector<int> v = { 50,60,70,80,90}, v1; //declaring v(with values), v1 as vector.
   vector<int>::iterator it;
   //declaring an ierator
   it = v.insert(v.begin(), 40);
   //inserting a value in v vector with specified the position at the beginning using the function begin().

   it = v.insert(v.begin(), 1, 30);
   //inserting a value with its size in v vector with specified the position at the beginning using the function begin().

   cout << "The vector1 elements are: ";
   for ( it = v.begin(); it != v.end(); ++it)
      cout << *it << " "<<endl; // printing the values of v vector

      v1.insert(v1.begin(),v.begin(),v.end());
      //inserting all values from beginning to end, by using begin() and end() function, of v
      vector in v1 vector pointing at the beginning using begin() function.
     
      cout << "The vector2 elements are: ";
      for (it = v1.begin(); it != v1.end(); ++it)
         cout << *it << " "<<endl; // printing the values of v1 vector
   return 0;
}

OutPut

The vector1 elements are: 
30
40
50
60
70
80
90
The vector2 elements are: 
30
40
50
60
70
80
90
raja
Published on 02-Apr-2019 18:13:05
Advertisements