lexicographically compare strings
how can i compare each element of string array[] lexicographically?
For example, if i want to find the smallest element in
1 2 3 4
|
folks[8] = {
"samwell", "jon", "margaery", "daenerys",
"tyrion", "sansa", "howard", "cersei"
};
|
would simply comparing each element like if (folk[0]<folk[1]) {do something} work??
would simply comparing each element like if (folk[0]<folk[1]) {do something} work?? |
Yes.
operator<
is overloaded for
std::string
to compare lexicographically.
For types other than strings, there is
std::lexicographical_compare
.
In linear time:
1 2 3 4 5 6 7 8 9 10 11 12
|
# include <iostream>
int main() {
std::string folks[8] = {
"samwell", "jon", "margaery", "daenerys",
"tyrion", "sansa", "howard", "cersei"
};
auto min = folks[0];
for (auto const &elt: folks)
min = elt < min? elt: min;
std::cout << min << "\n";
}
|
http://coliru.stacked-crooked.com/a/f2af1847c3ac1c6e
Last edited on
Topic archived. No new replies allowed.