C++容器排序函数sort

sort函数的使用

Tip:
1、头文件 < algorithm >
2、默认从小到大排序
3、可定制比较函数,即定制自己的“小于”函数

#include <deque>
#include <iostream>
#include <vector>
#include <algorithm>

class student{
public:
    student(std::string person_name, int person_score){
        name = person_name;
        score = person_score;
        }
        
    std::string name;
    int score;
    };
    

//自定义“小于”
bool compare(const int &a, const int &b){
    return a > b;
}

bool comp(const student &a, const student &b){
    return a.score > b.score;
}

int main()
{
using namespace std;
///array
    int a[10] = { 9, 0, 1, 2, 3, 7, 4, 5, 100, 10 };
    std::sort(a, a +10);
    for (int i = 0; i < 10; i++)
        cout << a[i] << "   ";
std::cout << std::endl;
/*
*   @deuqe  or vector or map
*/
// 	std::deque <int> c1;
    std::deque <int> c1;
	c1.push_back(9);
	c1.push_back(0);
	c1.push_back(1);
	c1.push_back(10);
    c1.push_back(3);
    c1.push_back(2);
	c1.push_back(7);
	c1.push_back(100);
	c1.push_back(5);
    c1.push_back(4);
    
    std::deque <int> c2(c1);
    cout << "The size of the deque is initially " << c1.size() << endl;
    std::cout << "###############   Init queue: " << std::endl;
    for (std::deque<int>::iterator it = c1.begin(); it != c1.end(); it++){
        std::cout << /*"c1[" << std::distance(c1.begin(),it) << "] :" << */*it << "   ";
    }
	std::cout << std::endl;
	
	std::cout << "###############   Default Sort queue: Ascending" << std::endl;
	sort(c1.begin(), c1.end());
    for (std::deque<int>::iterator it = c1.begin(); it != c1.end(); it++){
        std::cout << /*"c1[" << std::distance(c1.begin(),it) << "] :" << */*it << "   ";
    }
    std::cout << std::endl;
    
    std::cout << "###############   Sort queue: Descending" << std::endl;
	sort(c1.begin(), c1.end(),compare);
    for (std::deque<int>::iterator it = c1.begin(); it != c1.end(); it++){
        std::cout << /*"c1[" << std::distance(c1.begin(),it) << "] :" << */*it << "   ";
    }
    std::cout << std::endl;
    
    
    //类的排序
    std::vector <student> students;
    students.reserve(10);
    for(int i =0; i <10; i++){
        student one_student{"person"+std::to_string(i),c2.at(i)};
        std::cout << one_student.name << ":"<< one_student.score << "   " << std::endl;
        students.push_back(one_student);
    }
    std::sort(students.begin(), students.end(), comp);
    std::cout << "###############   Sort students queue: Descending" << std::endl;
    for(auto &it : students){
        std::cout << it.name << ":" << it.score << std::endl;
    }
}

备注:
关于sort数组时,数组总共有10个元素,a[0]~a[9], 但是缺是:sort(a, a+10); 那是因为sort方法实际上最后一位地址对应的数是不取的,如果换成a+9,则最后一个元素将不参与排序。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值