Swapping of subranges from different containers in C++


In this tutorial, we will be discussing a program to understand swapping of subranges of different containers in C++.

For this we will be provided with vectors and lists, and we need to swap some of their elements.

Example

 Live Demo

#include <algorithm>
#include <iostream>
#include <list>
#include <vector>
using namespace std;
int main(){
   vector<int> v = { -10, -15, -30, 20, 500 };
   list<int> lt = { 10, 50, 30, 100, 50 };
   swap_ranges(v.begin(), v.begin() + 3, lt.begin());
   for (int n : v)
      cout << n << ' ';
   cout << '\n';
   for (int n : lt)
      cout << n << ' ';
   cout << endl;
   return 0;
}

Output

10 50 30 20 500
-10 -15 -30 100 50

Updated on: 02-Mar-2020

40 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements