sort排序vector
时间: 2023-08-26 08:04:39 浏览: 48
要对vector进行排序,可以使用sort()函数。sort()函数可以接受一个表示容器的迭代器范围作为参数,然后对该范围内的元素进行排序。在排序时,我们需要传入一个比较函数,用于告诉sort()函数如何比较元素。
如果要对vector<int>进行排序,可以使用以下代码:
```
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main() {
vector<int> nums = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5};
sort(nums.begin(), nums.end()); // 默认升序排序
for(auto num : nums) {
cout << num << " ";
}
cout << endl;
sort(nums.begin(), nums.end(), greater<int>()); // 降序排序
for(auto num : nums) {
cout << num << " ";
}
cout << endl;
return 0;
}
```
如果要对二维数组进行排序,可以使用以下代码:
```
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<vector<int>> arr = {{3, 2}, {1, 4}, {7, 6}};
sort(arr.begin(), arr.end(), [](const vector<int>& a, const vector<int>& b) {
return a < b << ", " << v << "]" << endl;
}
return 0;
}
```
如果要对vector<pair<int,int>>的第二个元素进行排序,可以使用以下代码:
```
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
bool cmp(const pair<int, int>& a, const pair<int, int>& b) {
return a.second < b.second;
}
int main() {
vector<pair<int, int>> v = {{1, 4}, {2, 2}, {3, 5}, {4, 1}, {5, 3}};
sort(v.begin(), v.end(), cmp);
for(auto p : v) {
cout << p.first << " " << p.second << endl;
}
return 0;
}
```
这样就可以使用sort()函数对vector进行排序了。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* *3* [sort函数对结构体|pair对组|vector容器|map排序|二维数组的第x列 的排序](https://blog.csdn.net/weixin_73961973/article/details/129378897)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"]
[ .reference_list ]
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)