std::swap_ranges - cppreference.com

From cppreference.com

Defined in header

<algorithm>

template<classForwardIt1,classForwardIt2>ForwardIt2swap_ranges(ForwardIt1first1,ForwardIt1last1,ForwardIt2first2); (1)(constexpr since C++20)template<classExecutionPolicy,classForwardIt1,classForwardIt2>ForwardIt2swap_ranges(ExecutionPolicy&&policy,ForwardIt1first1,ForwardIt1last1,ForwardIt2first2); (2) (since C++17)1) Exchanges elements between the two ranges [first1, last1) and [first2, std::next(first2,std::distance(first1,next1))).

2) Same as (1), but executed according to policy.

This overload participates in overload resolution only if the value of the following expression is true:

std::is_execution_policy_v<std::decay_t<ExecutionPolicy>>

(until C++20)std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>>

(since C++20)If any of the following conditions is satisfied, the behavior is undefined:

The two ranges overlap.

There exists a pair of corresponding iterators iter1 and iter2 in the two ranges such that *iter1 is not

Swappable

with *iter2.

Parameters

first1, last1 - the pair of iterators defining the first

range

first2 - beginning of the second range policy - the

execution policy

to use Type requirements -ForwardIt1, ForwardIt2 must meet the requirements of

LegacyForwardIterator

. Return value

The past-the-end iterator of the second range.

Complexity

Exactly std::distance(first1,last1) swaps.

Exceptions

2) During the execution process:

If the temporary memory resources required for parallelization are not available,

std::bad_alloc

is thrown.

If an uncaught exception is thrown while accessing objects via an algorithm argument, the behavior is determined by the execution policy (for

standard policies

,

std::terminate

is invoked).

Notes

Implementations (e.g.

MSVC STL

) may enable vectorization when the iterator type satisfies

LegacyContiguousIterator

and swapping its value type calls neither non-trivial special member function nor

ADL

-found swap.

Possible implementation

template<classForwardIt1,classForwardIt2>constexpr//< since C++20ForwardIt2swap_ranges(ForwardIt1first1,ForwardIt1last1,ForwardIt2first2){for(;first1!=last1;++first1,++first2)std::iter_swap(first1,first2);returnfirst2;}Example

Demonstrates swapping of subranges from different containers.

Run this code

#include<algorithm>#include<iostream>#include<list>#include<vector>autoprint=[](autocomment,constauto&seq){std::cout<<comment;for(constauto&e:seq)std::cout<<e<<' ';std::cout<<'\n';};intmain(){std::vector<char>v{'a','b','c','d','e'};std::list<char>l{'1','2','3','4','5'};print("Before swap_ranges:\n""v: ",v);print("l: ",l);std::swap_ranges(v.begin(),v.begin()+3,l.begin());print("After swap_ranges:\n""v: ",v);print("l: ",l);}Output:

Before swap_ranges: v: a b c d e l: 1 2 3 4 5 After swap_ranges: v: 1 2 3 d e l: a b c 4 5 See also