×

C++ STL Tutorial

C++ STL Algorithm

C++ STL Arrays

C++ STL String

C++ STL List

C++ STL Stack

C++ STL Set

C++ STL Queue

C++ STL Vector

C++ STL Map

C++ STL Multimap

C++ STL MISC.

std::swap_ranges() function with example in C++

In this article we are going to see details of a standard library function swap_ranges() and its usages.
Submitted by Radib Kar, on August 21, 2020

C++ std::swap_ranges() Function

swap_ranges() swaps elements between two ranges.

Syntax

The syntax of the above function is:

ForwardIterator swap_ranges(
    ForwardIterator first1, 
    ForwardIterator last1, 
    ForwardIterator first2
    );

Parameter(s)

  • first1 : Iterator to beginning of a range.
  • last1 : Iterator to end of a range.
  • first2 : Iterator to beginning of another range.

We don't need to specify last2 as all elements of the first ranged needs to be swapped with the second range.

Say the ranges are:

{1, 2, 3, 4, 5, 6}
{11, 12, 13, 14, 15}

If we swap first three elements then after swapping it would be:

{11, 12, 13, 4, 5, 6}
{1, 2, 3, 14, 15} 

Below is the example & implementation of swap_ranges()

Example: C++ Implementation

#include <bits/stdc++.h>
using namespace std;

void printvector(vector<int> arr)
{
    for (auto it : arr)
        cout << it << " ";
    cout << endl;
}

int main()
{
    vector<int> arr1{ 1, 2, 3, 4, 5, 6 };
    vector<int> arr2{ 11, 12, 13, 14, 15 };

    //before swapping
    cout << "Before swapping, the ranges are:\n";
    printvector(arr1);
    printvector(arr2);
    
    //swap first three elements of arr1 with 
    //first three of arr2
    //first1=arr1.begin()
    //last1=arr1.begin()+3
    //first2=arr2.begin()
    swap_ranges(arr1.begin(), arr1.begin() + 3, arr2.begin());
    //After swapping

    cout << "After swapping, the ranges are:\n";
    printvector(arr1);
    printvector(arr2);

    return 0;
}

Output

Before swapping, the ranges are:
1 2 3 4 5 6 
11 12 13 14 15 
After swapping, the ranges are:
11 12 13 4 5 6 
1 2 3 14 15 

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.