简体   繁体   English

如何编写用户定义的std :: sort()比较

[英]How to write user defined compare for std::sort()

I have a two dimensional vector array vector<vector<int> > and I need to sort the vectors inside it in order. 我有一个二维向量数组vector<vector<int> > ,我需要对其中的向量进行排序。 So... I thought I would write a function which compare two vectors and then use sort() 所以...我想我会写一个比较两个向量的函数,然后使用sort()

However I couldn't understand and then was not able to find anywhere the proper syntax for this. 但是我不明白,然后在任何地方都找不到合适的语法。 Here is my compare function: 这是我的比较功能:

bool vectorcompare (vector<int> v, vector<int> w){ 
    for(int i=0; i<v.size(); i++){
        if(v[i]<w[i]) return 1;
        if(v[i]>w[i]) return 0;
    }
    return 1;
}

And then I call sort function, which doesn't work: 然后我调用了sort函数,该函数不起作用:

sort(vector.begin(),vector.end(), vectorcompare());

Anything I am doing wrong? 我做错了什么?

First, your compile error: 首先,您的编译错误:

sort(vector.begin(),vector.end(), vectorcompare());

vectorcompare is a function, not a type . vectorcompare是一个函数,而不是type That is, it's not an object that you can construct. 也就是说,它不是您可以构造的对象。 So you don't do () on it; 因此,您无需对此进行() you just pass the function as is: 您只需按原样传递函数即可:

sort(vector.begin(),vector.end(), vectorcompare);

Now, for a worse problem: 现在,一个更严重的问题:

bool vectorcompare (vector<int> v, vector<int> w)

Take your parameters by const& , not by value. const&而不是值来获取参数。 std::vector s are big; std::vector s很大; you shouldn't needlessly copy them. 您不必不必要地复制它们。

And an even worse problem: 还有一个更严重的问题:

for(int i=0; i<v.size(); i++){
    if(v[i]<w[i]) return 1;
    if(v[i]>w[i]) return 0;
}
return 1;

This does not constitute a strict-weak ordering . 这并不构成严格弱的排序 This provides less than or equals to , which is not a strict-weak ordering. 这提供了小于或等于 ,这不是严格弱的排序。 std::sort requires sorting based on a strict-weak ordering. std::sort需要基于严格弱排序进行排序。

You may not need to write your own comparison function. 您可能不需要编写自己的比较函数。 std::vector already has an operator< defined that performs the equivalent of std::lexicographical_compare . std::vector已经有一个operator<定义,它执行与std::lexicographical_compare等效的操作。 Have you tried simply calling std::sort on your vector<vector> ? 您是否尝试过在vector<vector>上简单地调用std::sort

Note: added my comment as this answer because the user found it helpful. 注意:添加我的评论作为此答案,因为用户发现它很有帮助。

Please look at this site, it has a nice example . 请查看此站点,它有一个很好的示例

In your case, you would call std::sort like this: 在您的情况下,您可以这样调用std::sort

sort(vector.begin(),vector.end(), vectorcompare);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM