vector从小到大排序
时间: 2023-09-28 12:07:37 浏览: 48
以下是一个示例代码,可以将vector从小到大排序:
```
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
std::vector<int> myVec{ 3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5 };
std::sort(myVec.begin(), myVec.end()); // 使用std::sort排序
for (auto i : myVec)
{
std::cout << i << " ";
}
std::cout << std::endl;
return 0;
}
```
输出:
```
1 1 2 3 3 4 5 5 5 6 9
```
使用`std::sort`函数可以对vector进行排序。该函数接受两个迭代器(begin和end),表示要排序的范围。在上面的代码中,我们使用`myVec.begin()`和`myVec.end()`作为参数,表示对整个vector进行排序。该函数会默认按照从小到大的顺序进行排序。排序后,我们可以使用一个for循环遍历vector并输出每个元素。
相关问题
定义一个空的vector,将用户输入的数组a[10]的10个数插入到vector中,在vector头部插入数b,用迭代器遍历vector并输出其中的元素值。然后将vector从小到大排序,删除vector尾部的元素,用迭代器遍历vector并输出其中的元素值。最后将vector清空。
下面是C++的实现代码:
```c++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> v; // 定义一个空的vector
int a[10];
for (int i = 0; i < 10; i++) {
cin >> a[i]; // 输入数组a
v.push_back(a[i]); // 将a[i]插入到vector的尾部
}
int b;
cin >> b;
v.insert(v.begin(), b); // 在vector头部插入数b
cout << "遍历vector并输出其中的元素值:" << endl;
for (vector<int>::iterator it = v.begin(); it != v.end(); it++) {
cout << *it << " ";
}
cout << endl;
sort(v.begin(), v.end()); // 对vector进行从小到大排序
v.pop_back(); // 删除vector尾部的元素
cout << "删除vector尾部的元素之后,再次遍历vector并输出其中的元素值:" << endl;
for (vector<int>::iterator it = v.begin(); it != v.end(); it++) {
cout << *it << " ";
}
cout << endl;
v.clear(); // 清空vector
return 0;
}
```
输入示例:
```
1 2 3 4 5 6 7 8 9 10
0
```
输出示例:
```
遍历vector并输出其中的元素值:
0 1 2 3 4 5 6 7 8 9 10
删除vector尾部的元素之后,再次遍历vector并输出其中的元素值:
0 1 2 3 4 5 6 7 8 9
```
C++ 写一个从小到大排序vector中元素的函数
我已经在之前的回答中给出了使用 `std::sort` 对 `vector` 中元素进行从小到大排序的 C++ 实现,这里再重新给出一遍:
```c++
#include <vector>
#include <algorithm>
void sortVector(std::vector<int>& vec) {
std::sort(vec.begin(), vec.end());
}
```
调用方式:
```c++
std::vector<int> vec = {5, 3, 8, 4, 2};
sortVector(vec);
```
注意,这里需要传入 `vector` 的引用,否则排序后的结果不会被保存。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.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)