用C ++对向量排序
可以使用std::sort()在C++中对向量进行排序。它在<algorithm>标头中定义。为了获得稳定的排序,使用了std::stable_sort。完全一样,sort()但保持相等元素的相对顺序。Quicksort(),mergesort()也可以根据要求使用。
算法
Begin
Decalre v of vector type.
Initialize some values into v in array pattern.
Print “Elements before sorting”.
for (const auto &i: v)
print all the values of variable i.
Print “Elements after sorting”.
Call sort(v.begin(), v.end()) function to sort all the elements of the v vector.
for (const auto &i: v)
print all the values of variable i.
End.这是在c++中对向量进行排序的简单示例:
示例
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> v = { 10, 9, 8, 6, 7, 2, 5, 1 };
cout<<"Elements before sorting"<<endl;
for (const auto &i: v)
cout << i << ' '<<endl;
cout<<"Elements after sorting"<<endl;
sort(v.begin(), v.end());
for (const auto &i: v)
cout << i << ' '<<endl;
return 0;
}输出结果
Elements before sorting 10 9 8 6 7 2 5 1 Elements after sorting 1 2 5 6 7 8 9 10
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短