How to add a range of elements of a list to another list in C++

1 Answer

0 votes
#include <iostream>
#include <list>

int main()
{
    // initializing lists 
    std::list<int> l1 = { 1, 2 }; 
    std::list<int> l2 = { 3, 4, 5, 6, 7, 8 }; 

    std::list<int>::iterator it2; 
    it2 = l2.begin();
    
    advance(it2, 2); // advance iterator by 2 positions
  
    // add elements from 3rd element to last in l2 at the end of l1
    l1.splice(l1.end(), l2, it2, l2.end()); 
    
    for (auto i : l1) {
        std::cout << i << " "; 
    }
}



/*
run:

1 2 5 6 7 8 

*/

 



answered Oct 15, 2025 by avibootz
...