an example of using splice() of C++ STL list

Since STL list iterator doesn't support random access, we can do "++i" twice but we cannot do "lst1.begin() + 2" in the code below.



👍 g++ -std=c++11 stl_list_splice.cpp
👍 ./a.out
A B C D E F G 
z y x w v u t s 
A B w v u C D E F G 
z y x t s 
👍 cat stl_list_splice.cpp 
#include <iostream>
#include <list>
using namespace std;

template<typename I>
void show(I i, I e) {
  for(; i != e; ++i)
    cout << *i << ' ';
  cout << endl;
} 

int main() {
  list<char> lst1, lst2; 
  for(int i = 0; i < 7; ++i)
    lst1.push_back(i + 'A');
  show(lst1.begin(), lst1.end());
  for(int i = 0; i < 8; ++i)
    lst2.push_back('z' - i);
  show(lst2.begin(), lst2.end());

  auto i = lst1.begin();
  ++i;
  ++i;
  auto j = lst2.begin();
  ++j;
  ++j;
  ++j;
  auto k = lst2.end();
  --k;
  --k;
  lst1.splice(i, lst2, j, k);
  show(lst1.begin(), lst1.end());
  show(lst2.begin(), lst2.end());
}