#include<iostream>
#include<algorithm>
#include<iterator>
using std::cout;
using std::endl;
int main()
{
const int SIZE = 10;
int a[ SIZE ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
std::ostream_iterator< int > outputIt( cout, " " );
cout<<"Array a contains:/n ";
std::copy( a, a + SIZE, outputIt );
std::swap( a[ 0 ], a[1] );
cout<<"/nArray a after swapping a[0] and a[1] "
<<"using swap:/n ";
std::copy( a, a + SIZE, outputIt );
std::iter_swap( &a[0], &a[1] );
cout<<"/nArray a after swapping a[0] and a[1] "
<<"using iter_swap:/n ";
std::copy( a, a + SIZE, outputIt );
std::swap_ranges( a, a + 5, a + 5 );
cout<< "/nArray a after swapping the first five elements/n"
<<"with the last five elements:/n ";
std::copy( a, a + SIZE, outputIt );
cout<<endl;
return 0;
}
本文演示了如何利用C++标准模板库(STL)中的swap, iter_swap及swap_ranges函数来交换数组中的元素。通过具体实例说明了这些函数的用法,并展示了交换前后数组的变化。

被折叠的 条评论
为什么被折叠?



