在 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP