C++ vector insert() element

Introduction

To insert an element at the end of the vector, we use the vector's.push_back() member function.

Example:

#include <vector> 

int main() //from   w ww .  j  av  a2  s. c  o m
{ 
    std::vector<int> v = { 1, 2, 3, 4, 5 }; 
    v.push_back(10); 
} 

This example inserts a value of 10 at the end of our vector.

Now we have a container of 6 elements: 1 2 3 4 5 10.

#include <iostream> 
#include <array> 
#include <vector> 
#include <ios> 


using namespace std; 

int main(int argc, char *argv [])
{   // w  w w . j a v a  2 s  . com

    using MyVector = vector<int>; 

    MyVector::const_iterator iter = myVector.cbegin() + 1; 
    myVector.insert(iter, 5); 
    myVector.erase(iter); 
        return 0; 
}



PreviousNext

Related