两值中较大和较小值
泛型函数std::min
返回两者之中较小值
泛型函数std::max
返回两者之中较大值
#include <iostream>
#include <algorithm>
using namespace std;
bool int_ptr_less( int* left, int* right )
{
return *left < *right;
}
int main()
{
int a = 10;
int b = 12;
long c = 13;
cout << std::min( a, b ) << endl;
cout << std::max( a, b ) << endl;
//注意,min和max都要求它们所接受的两个参数的型别必须一致,
//若不一致,可以考虑使用显示模板参数
cout << std::min<long>( b, c ) << endl;
//min和max的另一个版本,接收第三个参数作为比较准则
cout << *std::min( &a, &b, int_ptr_less ) << endl;
return 0;
}
两值互换
泛型函数std::swap
用来交换两对象的值
int a = 10;
int b = 12;
long c = 13;
std::swap( a, b );
//错误:必须型别一致
//std::swap<long>( a, c );
使用此函数来交换自定义的类型对象值也是可以的,只要其实现了赋值和复制函数,但有时针对复杂的自定义型别,会提供自己的特殊实作版本,如下:
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
class MyContainer
{
public:
//类内部实现交换
void swap( MyContainer& Other )
{
std::swap( m_Int, Other.m_Int );
m_Vec.swap( Other.m_Vec );
}
private:
int m_Int;
std::vector<int> m_Vec;
};
//为此复杂类重载全局函数swap
inline void swap( MyContainer& c1, MyContainer& c2 )
{
c1.swap( c2 );
}
交换两迭代器值
泛型函数std::iter_swap
可交换两个迭代器所指内容,注:此处是交换迭代器所指元素的内容,而不是迭代器本身内容,迭代器也是一对象。
int a = 10;
int b = 12;
//指针可看作是迭代器,
std::iter_swap( &a, &b );
//容器第1、2两个元素互相交换
std::vector<int> intVec;
intVec.push_back( 1 );
intVec.push_back( 2 );
std::iter_swap( intVec.begin(), intVec.begin() + 1 );
std::copy( intVec.begin(), intVec.end(),
std::ostream_iterator<int>( cout, " " ) );
cout << endl;