2013-04-28 67 views
0

Exacly如主题中所述:我可以用C++中的>,<比较字符串。 我没有得到任何错误,但不知道我会一直得到好的结果吗?我可以通过><在C++中比较字符串

string a = "aabbsd", b= "bsdds"; 
cout<<(a<b); 

结果只是运气吗?

+1

不需要很长时间查看参考并查看他们的工作。 – chris 2013-04-28 17:58:17

+0

你是什么意思的字符串?你的意思是这个长度!? – 2013-04-28 17:59:33

+0

这是字典对比btw。 – axiom 2013-04-28 18:00:57

回答

3

是的,你可以。它没有错。唯一需要注意的是操作的复杂性是线性的。

+0

太好了,谢谢。 – Yoda 2013-04-28 17:59:57

+0

@RobertKilar:所以在某些算法中使用比较时,应该意识到它对整体算法复杂性的影响。 – 2013-04-28 18:02:51

+1

在绝大多数常见情况下,操作是线性的这一事实是无关紧要的。只要找到第一个不相等的字符,比较就会结束。所以,除非你倾向于有很多共享重要前缀的字符串,否则你将不会遇到线性行为。事实上,如果不是大多数,即使不是所有情况,也是在很多情况下,行为是O(1)。 – 2013-04-28 18:45:48

1

这将触发字典对比。从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) 

比较两个字符串的内容。 1-2)检查lhs和rhs的内容是否相等,即lhs.size()== rhs.size(),lhs中的每个字符在rhs中的相同位置具有相同的字符。
3-6)按字典顺序比较lhs和rhs的内容。比较是通过一个等效于std :: lexicographical_compare的函数来执行的。