sort
algorithmThe sort
algorithm (from the header file <algorithm>
) has two forms:
sort(
begin, end);
sort(
begin, end, less-than-compare);
sort
algorithm for those containers.
sort
algorithm to
an unsorted container, such as a std::array
, vector
, string
,
or even a C array.
list
has a sort
method.
string s = "Kokopelli"; sort(s.begin(), s.end()); cout << s << '\n';
Keiklloop
string s = "Kokopelli"; sort(s.begin(), s.end(), less<char>); cout << s << '\n';
c.cc:2: error: expected primary-expression before ')' token
sort
want for the third argument?
less<>
?
string s = "Kokopelli"; sort(s.begin(), s.end(), less<char>()); cout << s << '\n';
Keiklloop
string s = "Kokopelli"; sort(s.begin(), s.end(), greater<char>()); cout << s << '\n';
poollkieK
bool lt(char a, char b) { return a < b; } int main() { string s = "Kokopelli"; sort(s.begin(), s.end(), lt); cout << s << '\n'; }
Keiklloop
string s = "Kokopelli"; sort(s.begin(), s.end(), [](char a, char b){return a<b;}); cout << s << '\n';
Keiklloop
bool lt(char a, char b) { return toupper(a) < toupper(b); } int main() { string s = "Kokopelli"; sort(s.begin(), s.end(), lt); cout << s << '\n'; }
eiKklloop
If you want to avoid duplicates, then use unique
.
bool lt(char a, char b) { return toupper(a) < toupper(b); } int main() { string s = "Kokopelli"; sort(s.begin(), s.end(), lt); auto it = unique(s.begin(), s.end()); s.resize(it-s.begin()); cout << s << '\n'; }
eiKklop
unique
assumes that its input is in order already.
Case-independent uniqueness doesn’t come free:
bool lt(char a, char b) { return toupper(a) < toupper(b); } bool eq(char a, char b) { return toupper(a) == toupper(b); } int main() { string s = "Kokopelli"; sort(s.begin(), s.end(), lt); auto it = unique(s.begin(), s.end(), eq); s.resize(it-s.begin()); cout << s << '\n'; }
eiKlop