zoukankan      html  css  js  c++  java
  • STL中常用算法

    一、排序 sort

    sort(first_pointer,first_pointer+n,cmp)
    默认为升序

    若要使用降序,自行写cmp 函数

    bool cmp(int a,int b)
    {
    return a<b; //升序排列,如果改为return a>b,则为降序
    }

    例如:
    方法一:定义比较函数(最常用)
    //情况一:数组排列
    int A[100];
    bool cmp1(int a,int b)//int为数组数据类型
    {
    return a>b;//降序排列
    //return a<b;//默认的升序排列
    }
    sort(A,A+100,cmp1);

    //情况二:结构体排序
    Student Stu[100];
    bool cmp2(Student a,Student b)
    {
    return a.id>b.id;//按照学号降序排列
    //return a.id<b.id;//按照学号升序排列
    }
    sort(Stu,Stu+100,cmp2);
    注:比较方法也可以放在结构体中或类中定义。

    //实现对map按value进行排序
    map中含两个值分别为key和value,map是按照key值进行排序的,若value值进行排序,如下:
    typedef pair<string, int> PAIR;
    int cmp(const PAIR & x, const PAIR & y)
    {
    return x.second > y.second;
    }

    map<string,int> m;
    vector<PAIR> vec;
    for (map<wstring,int>::iterator curr = m.begin(); curr != m.end(); ++curr)
    {
    vec.push_back(make_pair(curr->first, curr->second));
    }
    sort(vec.begin(), vec.end(), cmp);
    将map的key和value组成一个新的结构PAIR,一个PAIR型的vector存储map中的所有内容,对vecor按照value值进行排序。按顺序输出key:

    注意:如果是类的话,这个cmp的定义要放在类的外面,作为非成员函数 或者定义成 static 成员函数(推荐),不然编译会出错(如图)。

     正确写法:

    将cmp定义为类的static 成员函数

    class Solution {
    public:
        static  bool compare(vector<int> a, vector<int> b)    //将compare定义成 static  //不然会报如上错误
        {
            if (a[0] == b[0]) {
                return a[1] < b[1];
            } else {
                return a[0] > b[0];
            }
        }

        vector<vector<int>> ReconstructQueue(vector<vector<int>>& people)
        {
            sort(people.begin(), people.end(), compare);
            vector<vector<int>> res;
            for (int i = 0; i < people.size(); i++) {   
                res.insert(res.begin() + people[i][1], people[i]);
            }
            return res;
        }
    };
     
    二、 next_permutation  全排列

    #include<iostream>
    #include<algorithm>
    #include<string>
    using namespace std;

    int main()
    {
    string s;
    getline(cin,s);
    sort(s.begin(),s.end());
    do
    {
      cout<<s<<endl;
      }while(next_permutation(s.begin(),s.end()));
      return 0;
    }

    注: next_permutation 原型:
    #include <algorithm>
    bool next_permutation(iterator start,iterator end)

    注意:使用之前需要对所求全排列的数组进行升序排序。(因为它是基于当前数组去求下一个全排列)

  • 相关阅读:
    R 语言
    Maven
    IntelliJ IDEA
    Windows Terminal
    pip
    批处理编程案例
    Windows DOS命令批处理脚本
    Day15 T1 库特的向量
    Day12 T1 少女觉
    Day10 T2 邦德
  • 原文地址:https://www.cnblogs.com/sunshine1218/p/12088728.html
Copyright © 2011-2022 走看看