C++标准模板库vector的常用操作

2020-01-06 19:56:20丽君

五:排序

对vector整形进行排序


#include "stdlib.h"
#include <vector>
#include <algorithm>
using namespace std;
//升序比较函数
int compare1(const int &a, const int &b)
{
  return a < b;
}
//降序比较函数
int compare2(const int &a, const int &b)
{
  return a > b;
}
int main()
{
  vector<int> v;
  for (int i=0; i<10; i++)
  {
    v.push_back(rand() % 10);
  }
  //遍历输出
  printf("排序前数据:");
  for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
  {
    printf("%d ", *it);
  }
  //升序排序
  sort(v.begin(), v.end(), compare1);
  //遍历输出
  printf("n升序后数据:");
  for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
  {
    printf("%d ", *it);
  }
  //降序排序
  sort(v.begin(), v.end(), greater<int>());
  //遍历输出
  printf("n降序后数据:");
  for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
  {
    printf("%d ", *it);
  }
  getchar();
  return 1;
}

对存放类成员变量排序


#include <string>
#include <vector>
#include <algorithm>
using namespace std;
class Student {
public:  
  Student(string n, int c) :name(n), core(c) {}
  string  name;
  int    core;
};
//升序比较函数
bool compare1(const Student& s1, const Student& s2)
{
  return s1.core < s2.core;
}
//降序比较函数
bool compare2(const Student& s1, const Student& s2)
{
  return s1.core > s2.core;
}
int main()
{
  vector<Student> v;
  Student s1("aaaa", 97);
  Student s2("bbbb", 99);
  Student s3("cccc", 95);
  v.push_back(s1);
  v.push_back(s2);
  v.push_back(s3);
  printf("排序前数据:n");
  for (vector<Student>::iterator it = v.begin(); it != v.end(); it++)
  {
    printf("%s; %dn", ((*it).name).c_str(), (*it).core);
  }
  //升序排序
  sort(v.begin(), v.end(), compare1);
  printf("n升序后的数据:n");
  for (vector<Student>::iterator it = v.begin(); it != v.end(); it++)
  {
    printf("%s; %dn", ((*it).name).c_str(), (*it).core);
  }
  //降序排序
  sort(v.begin(), v.end(), compare2);
  printf("n降序后的数据:n");
  for (vector<Student>::iterator it = v.begin(); it != v.end(); it++)
  {
    printf("%s; %dn", ((*it).name).c_str(), (*it).core);
  }
  getchar();
  return 1;
}