如何对向量进行排序?
#include <algorithm>
bool comparisonFunc(char* c1, char* c2)
{
return strcmp(c1, c2) ? 0 : 1;
}
vector<char*> myVec;
vector<char*>::iterator itr;
sort(myVec.begin(), myVec.end(), comparisonFunc)
这是正确的还是有更好的方法?
#include <algorithm>
bool comparisonFunc(char* c1, char* c2)
{
return strcmp(c1, c2) ? 0 : 1;
}
vector<char*> myVec;
vector<char*>::iterator itr;
sort(myVec.begin(), myVec.end(), comparisonFunc)
Is that correct or is there a better way to do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
std::sort
需要一个“小于”谓词。您应该像这样实现您的comparisonFunc()
:(注意
const
;它们很重要。)您当前的实现不可能工作,因为您只是返回如果值是否相等。这些信息不足以进行排序 - 您需要知道哪一个较小,哪一个较大(当然,除非值相等)。
std::sort
expects a "less than" predicate. You should implement yourcomparisonFunc()
like this:(Note the
const
s; they are important.)Your current implementation couldn't possibly work because you just return if the values are equal or not. That information is not enough to sort - you need to know which one is smaller and which one is bigger (unless, of course, the values are equal).
使用现代 C++,您可以内联定义比较方法:
请注意,strcmp 返回 -1/0/+1 来指示序数,因此
0 比较。
With modern C++, you can define the comparison method inline:
Note that
strcmp
returns -1/0/+1 to indicate ordinality, hence the< 0
comparison.我更经常想要对指向记录的指针向量进行排序,而不仅仅是普通的 C 字符串...
这重新定义了 foo* 的比较,以便默认比较在排序中起作用。对我来说,这种风格更具声明性,而另一种风格则更具程序性。如果您需要多次订购,则使用默认值是有问题的;如果您想确保 foo*s 的所有有序集合都按相同的顺序排列,那就很好。
I more often want to sort a vector of pointer to records than just plain C-strings...
This redefines comparison of foo* such that the default comparison works in the sort. To me this style feels more declarative, the other more procedural. If you need multiple orderings this use of the default is problematic; if you want to be sure that all ordered collections of foo*s are in the same order it's good.