Search code examples
c++vectorcontainerscomparisonstandards

What does the > operator do when comparing two C++ containers?


For some reason, the ability exists in C++ to do greater-than/less-than comparisons between containers in C++, rather than between container elements. eg.

std::vector<int> vec1 = {1, 2, 3}, vec2 = {1, 2, 3, 4};
return vec1 > vec2;

The cppreference page gives the following explanation:

"true if the contents of the lhs are lexicographically greater than the contents of rhs, false otherwise".

What does "lexicographically greater" mean, in this context? And how is this at all useful?


Solution

  • Lexicologically greater would mean the same as in a dictionary. You can visualize it by replacing 1,2,3 with "abc" and 1,2,3,4 with "abcd". The string "abcd" will appear later on in the dictionary because it is lexicologically greater.

    If you had 2,2,3 (instead of 1,2,3) because 2 is lexicologically greater than 1, > will return true for the comparison between 2,2,3 and 1,2,3,4.

    The relative length of the containers does not matter. We are only looking at whether the sequence will appear in a dictionary before another sequence ('a' appears before 'b', '1' appears before '2').

    An example of where this is useful is when you need to know if a sequence comes before another sequence.