21xrx.com
2025-04-27 19:33:08 Sunday
文章检索 我的文章 写文章
C++中对vector进行排序的方法
2023-07-05 10:15:51 深夜i     57     0
C++ vector 排序方法 STL sort函数

vector是C++中常用的容器之一,可以使用其内置的sort()函数对其进行排序。下面就是对vector进行排序的方法。

1.使用sort()函数对vector进行排序

sort()函数是C++中STL提供的排序算法函数,它可以对各种容器进行排序,包括vector。要使用sort()函数需要包含头文件

如下例子:

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main(){
  vector<int> vi 8;
  sort(vi.begin(), vi.end());
  for (auto item : vi)
    cout << item << " ";
  
  cout << endl;
}

输出:

1 2 3 4 5 6 7 8

这里使用了begin()和end()函数来获取vector的首尾迭代器范围进行排序。

2.自定义排序规则

sort()函数的第三个参数可以指定排序规则,可以使用一个自定义的比较函数或者仿函数。比较函数接收两个参数,返回一个bool值,true表示第一个参数小于第二个参数,false则表示大于或相等。注意,如果自定义比较函数返回false,那么sort()函数就会认为这两个参数相等。

如下例子:

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
bool cmp(int a, int b)
  return a > b;
int main(){
  vector<int> vi 1;
  sort(vi.begin(), vi.end(), cmp);
  for (auto item : vi)
    cout << item << " ";
  
  cout << endl;
}

输出:

8 7 6 5 4 3 2 1

这里的自定义比较函数是定义了一个逆序排列的规则,把大的数排在前面。

以上就是在C++中对vector进行排序的方法,可以使用sort()函数对其进行简单的排序,也可以自定义排序规则使代码更加灵活。

  
  

评论区

请求出错了