From cppreference.com
template<std::indirectly_swappable<I>I2,classS2>friendconstexprvoiditer_swap(constcommon_iterator&x,conststd::common_iterator<I2,S2>&y)noexcept(/*see below*/);(since C++20)Swaps the objects pointed to by two underlying iterators.
Equivalent to ranges::iter_swap(std::get<I>(x.var),std::get<I2>(y.var)).
If x does not hold an I object or y does not hold an I2 object (i.e. at least one of x and y does not hold an iterator), the behavior is undefined.
(until C++26)If x does not hold an I object or y does not hold an I2 object (i.e. at least one of x and y does not hold an iterator):
If the implementation is
, a
occurs.
If the implementation is not hardened, the behavior is undefined.
(since C++26)This function template is not visible to ordinary
or
, and can only be found by
when std::common_iterator<I,S> is an associated class of the arguments.
Parameters
x, y - the iterators to the elements to swap Complexity
Constant.
Exceptions
specification:
noexcept(noexcept(ranges::iter_swap(std::declval<constI&>(),std::declval<constI2&>())))Example
Run this code
#include<algorithm>#include<iostream>#include<iterator>#include<string>#include<vector>intmain(){std::vector<std::string>v1{"1","2","3","4","5"},v2{"α","β","γ","δ","ε"};usingVI=std::vector<std::string>::iterator;usingCI=std::common_iterator<std::counted_iterator<VI>,std::default_sentinel_t>;CIfirst1{std::counted_iterator{v1.begin(),3}};CIfirst2{std::counted_iterator{v2.begin(),4}};CIlast{std::default_sentinel};autoprint=[&](autorem){std::cout<<rem<<"v1 = ";std::ranges::copy(v1,std::ostream_iterator<std::string>{std::cout," "});std::cout<<"\nv2 = ";std::ranges::copy(v2,std::ostream_iterator<std::string>{std::cout," "});std::cout<<'\n';};print("Before iter_swap:\n");for(;first1!=last&&first2!=last;++first1,++first2)iter_swap(first1,first2);// ADLprint("After iter_swap:\n");}Output:
Before iter_swap: v1 = 1 2 3 4 5 v2 = α β γ δ ε After iter_swap: v1 = α β γ 4 5 v2 = 1 2 3 δ ε Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
DR Applied to Behavior as published Correct behavior
C++20 variant was fully constexpr (P2231R1) but common_iterator was not also made constexpr See also
swaps the values of two objects
(function template)
swaps two ranges of elements
(function template & algorithm function object)
(C++20)
swaps the elements pointed to by two iterators
(function template)
(C++20)
swaps the values referenced by two dereferenceable objects
(customization point object)
(C++20)
swaps the objects pointed to by two underlying iterators
(function template)