Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




C++ - INSERT IN LIST


How to insert a new Item at the end of the List?


Let us say, we have a List that contains three names, Mohan, Kriti and Salim. And we want to insert a new name Mika at the end of the List.


We can use the push_back() Method to achieve the above.


Example :



#include <iostream>
#include <list>

using namespace std;

int main() {

    list<string> x = {"Mohan", "Kriti", "Salim"};
    x.push_back("Mika");
    for (string data : x)  
    {  
        cout << data << endl;  
    }
    
    return 0;    
}


Output :



  Mohan
  Kriti
  Salim
  Mika

So, in the above code we have created a List and initialised to the variable x.


list<string> x = {"Mohan", "Kriti", "Salim"};

Below is how the values are positioned in the List,

java_Collections

Next, we have used the push_back() method to add the new name Mika at the end of the List.


x.push_back("Mika");
java_Collections


And we get the below output,

Output :



  Mohan
  Kriti
  Salim
  Mika

How to insert a new Item at the beginning of the List?


Let us say, we have a List that contains three names, Mohan, Kriti and Salim. And we want to insert a new name Mika at the beginning of the List.


We can use the push_front() Method to achieve the above.


Example :



#include <iostream>
#include <list>

using namespace std;

int main() {

    list<string> x = {"Mohan", "Kriti", "Salim"};
    x.push_front("Mika");
    for (string data : x)  
    {  
        cout << data << endl;  
    }
    
    return 0;    
}


Output :



  Mika
  Mohan
  Kriti
  Salim

So, in the above code we have created a List and initialised to the variable x.


list<string> x = {"Mohan", "Kriti", "Salim"};

Below is how the values are positioned in the List,

java_Collections

Next, we have used the push_front() method to add the new name Mika at the end of the List.


x.push_front("Mika");
java_Collections


And we get the below output,

Output :



  Mohan
  Kriti
  Salim
  Mika