#include<bits/stdc .h>
using namespace std;
int main() {
vector <int> v = {1, 2 , 3, 2 , 1};
cout << v[0] << " " << v[1] << " " << v[2] << " " << v[3] << " " << v[4] << endl;
sort(v.begin(), v.end());
cout << v[0] << " " << v[1] << " " << v[2] << " " << v[3] << " " << v[4] << endl;
unique(v.begin(), v.end());
cout << v[0] << " " << v[1] << " " << v[2] << " " << v[3] << " " << v[4] << endl;
}
輸出是
1 2 3 2 1
1 1 2 2 3
1 2 3 2 3
我不明白什么是獨特的功能以及它是如何作業的?
uj5u.com熱心網友回復:
除此之外,bits/stdc .h在考慮 C 標準時,這不是正確的標題(請使用iostream,vector和algorithm)。來自:https ://en.cppreference.com/w/cpp/algorithm/unique
從范圍 [first, last) 中的每個連續等效元素組中消除除第一個元素之外的所有元素,并為范圍的新邏輯結束回傳一個過去的迭代器。
洗掉是通過移動范圍內的元素來完成的,這樣要擦除的元素會被覆寫
因此,向量的結尾可能包含“垃圾”,但這很好,因為它的新結尾也被回傳。
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
vector <int> v = {1, 2 , 3, 2 , 1};
cout << v[0] << " " << v[1] << " " << v[2] << " " << v[3] << " " << v[4] << endl;
sort(v.begin(), v.end());
cout << v[0] << " " << v[1] << " " << v[2] << " " << v[3] << " " << v[4] << endl;
auto new_end = unique(v.begin(), v.end());
auto b = v.begin();
while (b!=new_end) {
std::cout << *b << " ";
}
std::cout << "\n";
return 0;
}
演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/413492.html
標籤:
