Open In App

Swapping of subranges from different containers in C++

A container is a holder object that holds a collection of other objects. They are implemented as class templates, which allows a great flexibility in the types supported as elements.

Given some elements in vector and list, swap some of their elements.




// C++ program to swap subranges from different containers
#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() swaps the values starting from the beginning 
       to 3rd last values as per the parameters.
       Hence (-10, -15, -30) are swapped with (10, 50, 30). */
    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;
}

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

We can also swap ranges in two vectors.




// C++ program to swap subranges from different containers
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
  
int main()
{
    vector<int> v1 = { -10, -15, -30, 20, 500 };
    vector<int> v2 = { 10, 50, 30, 100, 50 };
      
    /* swap_ranges() swaps the values starting from the beginning 
       to 3rd last values as per the parameters.
       Hence (-10, -15, -30) are swapped with (10, 50, 30). */
    swap_ranges(v1.begin(), v1.begin() + 3, v2.begin());
  
    for (int n : v1)
        cout << n << ' ';
    cout << '\n';
  
    for (int n : v2)
        cout << n << ' ';
    cout << endl;
}

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

Article Tags :
C++