Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Swapping of subranges from different containers in C++

  • Last Updated : 11 Nov, 2018

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.

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




// 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



My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!