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.
#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;
}
|
Output:
10 50 30 20 500
-10 -15 -30 100 50
We can also swap ranges in two vectors.
#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(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
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...