容器数组自动排序
时间: 2023-09-02 08:06:11 浏览: 44
可以使用 STL 的 sort 函数来对容器数组进行自动排序,例如对一个 vector<int> 数组进行升序排序:
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> nums = {5, 2, 9, 1, 5, 6};
std::sort(nums.begin(), nums.end());
for (const auto& num : nums) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
```
输出结果为:1 2 5 5 6 9
也可以通过重载比较函数来实现对容器数组的降序排序,例如对一个 deque<int> 数组进行降序排序:
```cpp
#include <iostream>
#include <deque>
#include <algorithm>
bool cmp(int a, int b) {
return a > b;
}
int main() {
std::deque<int> nums = {5, 2, 9, 1, 5, 6};
std::sort(nums.begin(), nums.end(), cmp);
for (const auto& num : nums) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
```
输出结果为:9 6 5 5 2 1