operator==,!=,<,<=,>,>=(std::pair)

From Cppreference

Jump to: navigation, search
Defined in header <utility>

template< class T1, class T2 >
bool operator==( const pair<T1,T2>& lhs, const pair<T1,T2>& rhs );
(1)
template< class T1, class T2 >
bool operator!=( const pair<T1,T2>& lhs, const pair<T1,T2>& rhs );
(2)
template< class T1, class T2 >
bool operator<( const pair<T1,T2>& lhs, const pair<T1,T2>& rhs );
(3)
template< class T1, class T2 >
bool operator<=( const pair<T1,T2>& lhs, const pair<T1,T2>& rhs );
(5)
template< class T1, class T2 >
bool operator>( const pair<T1,T2>& lhs, const pair<T1,T2>& rhs );
(4)
template< class T1, class T2 >
bool operator>=( const pair<T1,T2>& lhs, const pair<T1,T2>& rhs );
(6)

1-2) Tests if both elements of lhs and rhs are equal, that is, compares lhs.first with rhs.first and lhs.second with rhs.second

3-6) Compares lhs and rhs lexicographically, that is, compares the first elements and only if they are equivalent, compares the second elements.

[edit] Parameters

lhs, rhs - pairs to compare

[edit] Return value

1) true if both lhs.first == rhs.first and lhs.second == rhs.second, otherwise false

2) true if either lhs.first != rhs.first or lhs.second != rhs.second, otherwise false

3) If lhs.first<rhs.first, returns true. Otherwise, if rhs.first<lhs.first, returns false. Otherwise, if lhs.second<rhs.second, returns true. Otherwise, returns false.

4) !(lhs < rhs)

5) rhs < lhs

6) !(rhs < lhs)

[edit] Example

Because operator< is defined for pairs, containers of pairs can be sorted.

#include <iostream>
#include <utility>
#include <vector>
#include <algorithm>
 
int main()
{
    std::vector<std::pair<int, std::string>> v = { {2, "baz"},
                                                   {2, "bar"},
                                                   {1, "foo"} };
    std::sort(v.begin(), v.end());
 
    for(auto p: v) {
        std::cout << "(" << p.first << "," << p.second << ")\n";
    }
}

Output:

(1,foo)
(2,bar)
(2,baz)