C++: Compare a List of Strings


Given a list of arbitrarily many strings, show how to:

  • test if they are all lexically equal
  • test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order)

Each of those two tests should result in a single true or false value, which could be used as the condition of an if statement or similar. If the input list has less than two elements, the tests should always return true.

There is no need to provide a complete program & output: Assume that the strings are already stored in an array/list/sequence/tuple variable (whatever is most idiomatic) with the name strings, and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs), with as little distractions as possible.

Assuming that the strings variable is of type T<std::string> where T is an ordered STL container such as std::vector:

#include <algorithm>
#include <string>

std::all_of( ++(strings.begin()), strings.end(),
[&](std::string a){ return a == strings.front(); } )  // All equal

std::is_sorted( strings.begin(), strings.end(),
[](std::string a, std::string b){ return !(b < a); }) )  // Strictly ascending


Content is available under GNU Free Documentation License 1.2.