c++vectorrelational-operators

Comparing 2 vectors using relational operators


I tried comparing 2 vectors using relational operators.

vector<int>v1 {1, 2, 3};
vector<int>v2 {3, 40, 4};

cout<<(v1<v2)<<endl;    // Prints 1
cout<<(v1>v2)<<endl;    // Prints 0

What I am not sure of is on what basis is the comparison happening? It seems that it is comparing element by element. But I can't find any resource regarding that. Any help regarding a resource or an explanation would be appreciated.


Solution

  • What I am not sure of is on what basis is the comparison happening?

    The C++ reference says:

    template< class T, class Alloc >
    bool operator<( const std::vector<T,Alloc>& lhs,
                    const std::vector<T,Alloc>& rhs );
    

    Compares the contents of lhs and rhs lexicographically.

    Lexicographic order could be roughly said as ordering the contents in alphabetic order.

    Thus, when you compare v1 > v2, it'll return true once the contents in it of the lhs are lexicographically greater than the contents of rhs.

    Exception: However, if both vectors are equal, then the comparison will return false:

    std::vector<int> v1{1, 2, 3};
    std::vector<int> v2{1, 2, 3};
    std::cout << (v1 > v2) + ' ' + (v1 < v2) << std::endl;