c++中sort函数的用法,如何自定义排序方法(数组,结构体,向量)

0 参数意义

Sort函数有三个参数:

(1)第一个是要排序的数组的起始地址。

(2)第二个是结束的地址(最后一位要排序的地址)

(3)第三个参数是排序的方法,可以是从大到小也可是从小到大,还可以不写第三个参数,此时默认的排序方法是从小到大排序。

1 给数组排序 默认排序+自定义排序

#include<iostream>

#include<algorithm>
using namespace std;

bool complare(int a,int b)
{
    return a>b;
}

void print(int a[]) {
	for(int i=0;i<10;i++)
  	 cout<<a[i]<<" ";
 	 cout<<endl;
}

int main()
{
	
    int a[10]={9,6,3,8,5,2,7,4,1,0};
    print(a);//9,6,3,8,5,2,7,4,1,0 
   
    sort(a,a+10); //默认输出从小到大 
    print(a);//0 1 2 3 4 5 6 7 8 9 
   
    sort(a,a+10,complare);//按照从大大小输出 
    print(a);//9 8 7 6 5 4 3 2 1 0 
    return 0;
}

2给结构体排序

假设自己定义了一个结构体node

struct node
{
  int a;
  int b;
  double c;
}

有一个node类型的数组node arr[100],想对它进行排序:先按a值升序排列,如果a值相同,再按b值降序排列,如果b还相同,就按c降序排列。就可以写这样一个比较函数:

以下是代码片段:

bool cmp(node x,node y)
{
   if(x.a!=y.a) return x.a<y.a;
   if(x.b!=y.b) return x.b>y.b;
   return x.c>y.c;
}

3给向量vector排序

/*
/*
题目描述:
磁盘的容量单位有M、G、T,其关系为 1T = 1000G、1G = 1000M,如样例所示先输入磁盘的个数,再依次输入磁盘的容量大小,然后按照从小到大的顺序对磁盘容量进行排序并输出。

输入样例:

3
20M
1T
3G

输出样例:

20M
3G
1T
*/ 

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

int StrToInt(string str) //结尾对号入座 ,转化成整数 
{
    if (str[str.size() - 1] == 'M') {
        return stoi(str.substr(0, str.size() - 1)); //截取[0,size-1)的字符,左闭右开区间 
    } else if (str[str.size() - 1] == 'G') {
        return stoi(str.substr(0, str.size() - 1)) * 1000;
    } else if (str[str.size() - 1] == 'T') {
        return stoi(str.substr(0, str.size() - 1)) * 1000000;
    }

    return 0;
}

bool Compare(const string &strA, const string &strB) // 
{
//	cout<<"strA="<< strA <<endl;
//	cout<<"strB="<< strB <<endl;
    int a = StrToInt(strA);
    int b = StrToInt(strB);

    // 升序排序
    return a < b;
}

int  main(void)
{
    int n;
    while (cin >> n) {
        string str;
        vector<string> vec;

        while (n--) {
            cin >> str;
            vec.push_back(str); //向量中添加元素 
        }

        sort(vec.begin(), vec.end(), Compare);//Sort(start,end,排序方法) 

        for (auto i : vec) {
            cout << i << endl;
        }
    }
    
    return 0;
}


来自:
https://blog.csdn.net/Charmve/article/details/105777990?depth_1-utm_source=distribute.pc_feed.none-task-blog-alirecmd-4&request_id=&utm_source=distribute.pc_feed.none-task-blog-alirecmd-4

不太清楚vector用法的可以参考这里

https://blog.csdn.net/qq_41398619/article/details/105836097

stio的用法

/*
 stoi(字符串,起始位置,n进制),将 n 进制的字符串转化为十进制
 stoi(str, 0, 2); //将字符串 str 从 0 位置开始到末尾的 2 进制转换为十进制
*/ 

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string str = "1010";
    int a = stoi(str, 0, 2);
    cout << a << endl; //输出10 
        return 0;
}

部分内容转自:https://www.cnblogs.com/epep/p/10959627.html

原创文章 36 获赞 8 访问量 2750

猜你喜欢

转载自blog.csdn.net/qq_41398619/article/details/105834653