1、std::swap
描述:
交换两个对象的值。
函数定义:
template< class T >
void swap( T& a, T& b );
template< class T >
void swap( T& a, T& b ) noexcept(/* see below */);
template< class T >
constexpr void swap( T& a, T& b ) noexcept(/* see below */);
参数:
a, b - 要交换的值
示例:
int main()
{
int nA = 1, nB = 2;
std::swap(nA, nB);
std::cout << nA << std::endl;//2
std::cout << nB << std::endl;//1
std::vector<int> vecInt1 = {1,2};
std::vector<int> vecInt2 = {3,4};
std::swap(vecInt1, vecInt2);
auto print = [](int nA) {std::cout << nA << " "; };
std::for_each(vecInt1.begin(), vecInt1.end(), print);//3 4
std::cout << std::endl;
std::for_each(vecInt2.begin(), vecInt2.end(), print);//1 2
}
2、std::iter_swap
描述:
交换两个迭代器所指向的元素。
函数定义:
template< class ForwardIt1, class ForwardIt2 >
void iter_swap( ForwardIt1 a, ForwardIt2 b );
template< class ForwardIt1, class ForwardIt2 >
constexpr void iter_swap( ForwardIt1 a, ForwardIt2 b );
参数:
a, b - 指向要交换的元素的迭代器
可能的实现:
template<class ForwardIt1, class ForwardIt2>
constexpr void iter_swap(ForwardIt1 a, ForwardIt2 b) // C++20 起为 constexpr
{
using std::swap;
swap(*a, *b);
}
示例:
int main()
{
std::vector<int> vecInt1 = {1,2};
std::vector<int> vecInt2 = {3,4};
std::iter_swap(vecInt1.begin(), vecInt2.begin());
auto print = [](int nA) {std::cout << nA << " "; };
std::for_each(vecInt1.begin(), vecInt1.end(), print);//3 2
std::cout << std::endl;
std::for_each(vecInt2.begin(), vecInt2.end(), print);//1 4
}
3、std::swap_ranges
描述:
交换两个范围的元素。
在范围 [first1, last1) 和始于 first2 的另一范围间交换元素。
函数定义:
template< class ForwardIt1, class ForwardIt2 >
ForwardIt2 swap_ranges( ForwardIt1 first1, ForwardIt1 last1,
ForwardIt2 first2 );
template< class ForwardIt1, class ForwardIt2 >
constexpr ForwardIt2 swap_ranges( ForwardIt1 first1, ForwardIt1 last1,
ForwardIt2 first2 );
参数:
first1, last1 - 要交换的第一个元素范围
first2 - 要交换的第二个元素范围的起始
返回值:
返回始于 first2 的范围中被交换的最末元素后一元素的迭代器。
可能的实现:
template<class ForwardIt1, class ForwardIt2>
ForwardIt2 swap_ranges(ForwardIt1 first1,
ForwardIt1 last1,
ForwardIt2 first2)
{
while (first1 != last1) {
std::iter_swap(first1++, first2++);
}
return first2;
}
示例:
int main()
{
std::vector<int> vecInt1 = {1,2,3,4,5};
std::vector<int> vecInt2 = {6,7,8,9,10};
std::swap_ranges(vecInt1.begin(), vecInt1.begin()+3, vecInt2.begin());
auto print = [](int nA) {std::cout << nA << " "; };
std::for_each(vecInt1.begin(), vecInt1.end(), print);//6 7 8 4 5
std::cout << std::endl;
std::for_each(vecInt2.begin(), vecInt2.end(), print);//1 2 3 9 10
}