我正在尝试使用插入排序对字符串向量进行排序。
这是我的代码:
void insertionsort(std::vector<std::string> &strings)
{
typedef std::vector<std::string>::size_type size_type;
for(size_type i = 0;i < strings.size(); i++)
{
std::string const tmp = strings[i];
size_type j = i - 1;
while(j >= 0 && tmp < strings[j]) //this is the problem
{
strings[j + 1]= strings[j];
j--;
}
strings[j + 1]=tmp;
}
}
它给了我错误:
无符号表达式的比较 >= 0 始终为真
如果我使用 j > 0,该函数工作正常。但它完全忽略了字符串的第一行。
例如,如果我有:
2 line1
3 line2
4 line3
5 line4
1 line5
然后它给了我:
2 line1
1 line5
3 line2
4 line3
5 line4
vector<T>::size_type
是通过定义无符号所以j >= 0
不能是假的。你应该使用vector<T>::difference_type
.
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句