如何利用标准库sort函数进行排序

参考资料:《C++ Primer》


一、对向量(vector)中的元素排序     

#include <vector>                                 ///可能需要
#include <algorithm>                              ///可能需要


std::vector<int> nVec(8,124);                     ///建立8个int型元素,将8个元素通通赋值为124
std::sort(nVec.begin(),nVec.end());               ///对nVec中的元素从小到大排序
sort( nVec.begin(), nVec.begin()+nVec.size()/2 ); ///只对向量的前一半进行排序
 

二、对内置数组指针对排序

#include <algorithm>                   ///可能需要

int ia[7] = { 10, 7, 9, 5, 3, 7, 1 };
std::sort(ia,ia+7);                    ///对ia数组中的7个值按照从小到大排序
std::sort(ia,ia+4);                    ///只对前4个元素从小到大排序

猜你喜欢

转载自blog.csdn.net/Johnisjohn/article/details/86692904