The Wayback Machine - https://web.archive.org/web/20160319033733/http://en.cppreference.com/w/cpp/algorithm/swap_ranges
Namespaces
Variants
Actions

std::swap_ranges

From cppreference.com
< cpp‎ | algorithm
 
 
Algorithm library
Execution policies (C++17)
Non-modifying sequence operations
(C++11)(C++11)(C++11)
(C++17)
Modifying sequence operations
Operations on uninitialized storage
Partitioning operations
Sorting operations
Binary search operations
Set operations (on sorted ranges)
Heap operations
(C++11)
Minimum/maximum operations
(C++11)
(C++17)

Permutations
Numeric operations
C library
 
Defined in header <algorithm>
template<class ForwardIt1, class ForwardIt2 >
ForwardIt2 swap_ranges( ForwardIt1 first1, ForwardIt1 last1, ForwardIt2 first2 );

Exchanges elements between range [first1, last1) and another range starting at first2.

Contents

[edit]Parameters

first1, last1 - the first range of elements to swap
first2 - beginning of the second range of elements to swap
Type requirements
-
ForwardIt1, ForwardIt2 must meet the requirements of ForwardIterator.
-
The types of dereferenced ForwardIt1 and ForwardIt2 must meet the requirements of Swappable

[edit]Return value

Iterator to the element past the last element exchanged in the range beginning with first2.

[edit]Possible implementation

template<class ForwardIt1, class ForwardIt2> ForwardIt2 swap_ranges(ForwardIt1 first1, ForwardIt1 last1, ForwardIt2 first2){while(first1 != last1){std::iter_swap(first1++, first2++);}return first2;}

[edit]Example

Demonstrates swapping of subranges from different containers

#include <algorithm>#include <list>#include <vector>#include <iostream>int main(){std::vector<int> v ={1, 2, 3, 4, 5};std::list<int> l ={-1, -2, -3, -4, -5};   std::swap_ranges(v.begin(), v.begin()+3, l.begin());   for(int n : v)std::cout<< n <<' ';std::cout<<'\n';for(int n : l)std::cout<< n <<' ';std::cout<<'\n';}

Output:

-1 -2 -3 4 5 1 2 3 -4 -5

[edit]Complexity

linear in the distance between first and last

[edit]See also

swaps the elements pointed to by two iterators
(function template)[edit]
swaps the values of two objects
(function template)[edit]
parallelized version of std::swap_ranges
(function template)[edit]
close