1.常用排序算法
算法简介:
sort对容器内元素进行排序random_shuffle洗牌指定范围内的元素随机调整次序merge容器元素合并并存储到另一容器中reverse反转指定范围的元素2.sort排序算法/*函数原型:sort(iteratorbeg,iteratorend,_pred);按照从小到大的顺序排列顺序beg开始迭代器end结束迭代器_pred谓词*///提供谓词classGreater20{public:booloperator()(intval,intval2){returnvalval2;}};//打印函数voidmyPrint(intval){coutval"";}voidtest01(){vectorintv;v.push_back(10);v.push_back(40);v.push_back(0);v.push_back(40);v.push_back(20);v.push_back(40);//利用sort进行升序sort(v.begin(),v.end());for_each(v.begin(),v.end(),myPrint);coutendl;//利用sort进行降序sort(v.begin(),v.end(),Greater20());for_each(v.begin(),v.end(),myPrint);}intmain(){test01();system("pause");return0;}.random_shuffle指定范围内的元素随机调整次序
/*函数原型:random_shuffle(iteratorbeg,iteratorend);指定范围内的元素随机调整次序beg开始迭代器end结束迭代器*/voidmyPrint(intval){coutval"";}voidtest01(){//虽然打乱了,但是每次启动后大乱顺序都一样//如果想要每次打乱顺序不同需要加上随机数种子srand((unsignedint)time(NULL));vectorintv;for(inti=0;i10;i++){v.push_back(i);}//利用洗牌算法打乱顺序random_shuffle(v.begin(),v.end());for_each(v.begin(),v.end(),myPrint);}intmain(){test01();system("pause");return0;}4.merge两个容器元素合并,并存储到另一个容器中
/*函数原型:merge(iteratorbeg1,iteratorend1,iteratorbeg2,iteratorend2,iteratordest);容器元素合并,并存储到另一个容器中注意:两个容器必须是有序的beg1容器1开始迭代器end1容器1结束迭代器beg2容器2开始迭代器end2容器2结束迭代器dest目标容器开始迭代器*/voidmyPrint(intval){coutval"";}voidtest01(){//开始容器v1v2vectorintv1;vectorintv2;for(inti=0;i10;i++){v1.push_back(i);v2.push_back(i+1);}//目标容器vectorintdest;//目标容器没有指定空间如果忘记会产生报错dest.resize(v1.size()+v2.size());merge(v1.begin(),v1.end(),v2.begin(),v2.end(),dest.begin());for_each(dest.begin(),dest.end(),myPrint);}intmain(){test01();system("pause");return0;}5.reverse将容器内元素进行反转
/*函数原型:reverse(iteratorbeg,iteratorend);反转指定范围的元素beg开始迭代器end结束迭代器*/voidmyPrint(intval){coutval"";}voidtest01(){vectorintv;v.push_back(10);v.push_back(0);v.push_back(50);v.push_back(20);v.push_back(40);cout"反转前"endl;for_each(v.begin(),v.end(),myPrint);coutendl;cout"反转后"endl;reverse(v.begin(),v.end());for_each(v.begin(),v.end(),myPrint);}intmain(){test01();system("pause");return0;}