Bootstrap

cpp_sort

0. 修改 排序方式(升序 改为 降序)

// 默认升序排列, 改成降序排列
bool cmp(int a,int b)
{
  return a>b;
}
sort(x,x+4,cmp);

1. 排序向量的一部分

参考文献

// sort algorithm example
#include <iostream>     // std::cout
#include <algorithm>    // std::sort
#include <vector>       // std::vector

bool myfunction (int i,int j) { return (i<j); }

struct myclass {
  bool operator() (int i,int j) { return (i<j);}
} myobject;

int main () {
  int myints[] = {32,71,12,45,26,80,53,33};
  std::vector<int> myvector (myints, myints+8);// 32 71 12 45 26 80 53 33

  // using default comparison (operator <):
  std::sort (myvector.begin(), myvector.begin()+4);//(12 32 45 71)26 80 53 33

  // using function as comp
  std::sort (myvector.begin()+4, myvector.end(), myfunction);// 12 32 45 71(26 33 53 80)

  // using object as comp
  std::sort (myvector.begin(), myvector.end(), myobject);//(12 26 32 33 45 53 71 80)

  // print out content:
  std::cout << "myvector contains:";
  for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';

  return 0;
}

2. 一个vector的各个元素是 class的 对象排序

class Edge {
	private:
		int l,r,val;
		};
//从小到大排序
bool sortByVal(Edge &lhs, Edge &rhs) {
	return lhs.getVal() < rhs.getVal();
}
sort(edge.begin(), edge.end(), sortByVal);

3. 结构体的二级排序

#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
struct link
{
    int a,b;
};
bool cmp(link x,link y)
{
    if(x.a==y.a) //highlight
        return x.b>y.b; //highlight
    return x.a>y.a;
}
int main()
{
    link x[4];
    for(int i=0;i<4;i++)
        cin>>x[i].a>>x[i].b;
    sort(x,x+4,cmp);
    for(int i=0;i<4;i++)
        cout<<x[i].a<<' '<<x[i].b<<endl;
    return 0;
 }

4.

;