CS253 Sort Algorithm
sort
algorithmThe sort
algorithm (from the header file <algorithm>
) has two forms:
sort(
begin, end);
sort(
begin, end, 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 compare(char a, char b) { return a < b; } int main() { string s = "Kokopelli"; sort(s.begin(), s.end(), compare); cout << s << '\n'; }
Keiklloop
string s = "Kokopelli"; sort(s.begin(), s.end(), [](char a, char b){return a<b;}); cout << s << '\n';
Keiklloop
bool compare(char a, char b) { return toupper(a) < toupper(b); } int main() { string s = "Kokopelli"; sort(s.begin(), s.end(), compare); cout << s << '\n'; }
eiKklloop
If you want to avoid duplicates, then use unique
.
bool compare(char a, char b) { return toupper(a) < toupper(b); } int main() { string s = "Kokopelli"; sort(s.begin(), s.end(), compare); auto it = unique(s.begin(), s.end()); s.resize(it-s.begin()); cout << s << '\n'; }
eiKklop
Modified: 2017-04-20T22:16 User: Guest Check: HTML CSSEdit History Source |
Apply to CSU |
Contact CSU |
Disclaimer |
Equal Opportunity Colorado State University, Fort Collins, CO 80523 USA © 2015 Colorado State University |