Reputation: 18068
Exacly as stated in the subject: May I compare strings by >
, <
in c++.
I get no errors but not sure will I always get good result?
string a = "aabbsd", b= "bsdds";
cout<<(a<b);
Is the result is just a luck?
Upvotes: 0
Views: 154
Reputation: 13207
This will trigger a lexicographical comparison. From cppreference:
operator==,!=,<,<=,>,>=(std::basic_string)
C++ Strings library std::basic_string
template< class T, class Alloc >
bool operator==( basic_string<T,Alloc>& lhs, basic_string<T,Alloc>& rhs );
(1)
template< class T, class Alloc >
bool operator!=( basic_string<T,Alloc>& lhs, basic_string<T,Alloc>& rhs );
(2)
template< class T, class Alloc >
bool operator<( basic_string<T,Alloc>& lhs, basic_string<T,Alloc>& rhs );
(3)
template< class T, class Alloc >
bool operator<=( basic_string<T,Alloc>& lhs, basic_string<T,Alloc>& rhs );
(4)
template< class T, class Alloc >
bool operator>( basic_string<T,Alloc>& lhs, basic_string<T,Alloc>& rhs );
(5)
template< class T, class Alloc >
bool operator>=( basic_string<T,Alloc>& lhs, basic_string<T,Alloc>& rhs );
(6)
Compares the contents of two strings.
1-2) Checks if the contents of lhs and rhs are equal, that is, lhs.size() == rhs.size() and each character in lhs has equivalent character in rhs at the same position.
3-6) Compares the contents of lhs and rhs lexicographically. The comparison is performed by a function equivalent to std::lexicographical_compare.
Upvotes: 1
Reputation: 6606
Yes you can. Nothing wrong in it. Only thing to note is that the complexity of operation is linear.
Upvotes: 3