c++ sort函数怎么使用
时间: 2024-10-20 15:02:00 浏览: 28
`sort`函数是C++标准库中的一个函数,通常位于`<algorithm>`头文件中,用于对容器(如`std::vector`、`std::array`等)的内容进行排序。它的基本语法如下:
```cpp
template <class RandomIt>
void sort(RandomIt first, RandomIt last);
```
其中:
- `first`:指定排序范围的起始迭代器。
- `last`:指定排序范围的结束迭代器(不包括该位置)。
如果你想对容器内的元素按照升序进行整数排序,可以像下面这样使用:
```cpp
std::vector<int> numbers = {5, 2, 9, 1, 7};
std::sort(numbers.begin(), numbers.end());
```
如果你需要自定义排序规则,比如按字符串长度排序,你可以提供一个比较函数作为第二个模板参数:
```cpp
std::vector<std::string> words = {"apple", "banana", "cherry"};
std::sort(words.begin(), words.end(), [](const std::string& a, const std::string& b) {
return a.length() < b.length();
});
```
这里使用了lambda表达式来进行比较。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20250102104920.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)