C++标准库笔记:算法--min/max/swap/iter_swap
来源:互联网 发布:linux 剩余空间 编辑:程序博客网 时间:2024/05/29 15:52
两值中较大和较小值
泛型函数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;};//为此复杂类重载全局函数swapinline 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;
阅读全文
0 0
- C++标准库笔记:算法--min/max/swap/iter_swap
- vc中对标准库std::min,max,swap的支持问题
- 变异算法之交换(swap, swap_ranages, iter_swap)
- Min-Min算法和Max-Min算法
- Min-Min算法和Max-Min算法
- Min-Min算法 Max-Min算法
- Min-Min算法和Max-Min算法
- Min-Min算法 Max-Min算法
- 泛型算法系列14:random_shuffle()&&iter_swap()&&swap()
- C++标准库---advance()&distance()&iter_swap()
- Max-Min算法实现
- 标准库std::min/std::max与min/max宏冲突
- MIN-max极差标准标准化
- STL 之swap, iter_swap, swap_ranges
- STL 之swap, iter_swap, swap_ranges
- 通用工具Utilities(二)----min max swap offsetof
- max()、min()、swap()简单介绍
- Max-Min 带宽公平分配算法
- 生成器
- Pycharm的激活
- [机器学习入门] 李宏毅机器学习笔记-14 (Unsupervised Learning: Linear Dimension Reduction;无监督学习:线性降维)
- 解决因为手机设置字体大小导致h5页面在webview中变形的BUG
- 《汇编语言程序设计教程》人民邮电出版社第二版习题及参考答案
- C++标准库笔记:算法--min/max/swap/iter_swap
- 百度编辑器UEditor常用设置函数大全
- Together项目IOS平台开发11
- 微信 嗅探id 好友
- 红黑树概念、红黑树的插入及旋转操作图解--转载
- JavaScript和HTML及CSS的通俗解释
- 138. Copy List with Random Pointer
- LeetCode Array
- 边沿检测&门控时钟