对向量进行排序的最快方法是什么

what is the fastest way of sorting a vector?

本文关键字:方法 是什么 排序 向量      更新时间:2023-10-16

我想根据距离变量对"mystruct"进行排序,最快的方法是什么?

struct MyStruct {
   int scale;
   bool pass;
   float distance;
};
vector<MyStruct> mystruct;
...
sort (mystruct.begin(), mystruct.begin() + mystruct.size());
//this doesn't work since is trying to sort by "MyStruct" and not by a number

如果我有

vector<float> myfloat;
...
sort (myfloat.begin(), myfloat.begin() + myfloat.size());

然后将完美工作。

您需要为结构编写自己的operator<

它应该是类似的东西

bool operator<( const MyStruct& s1, const MyStruct& s2 )
{
    // compare them somehow and return true, if s1 is less than s2
    // for your case, as far as I understand, you could write
    // return ( s1.distance < s2.distance );
}

另一种选择是编写一个函数对象,但在这里没有必要,编写operator<更容易(对于初学者)

您需要为排序函数提供一个函子,或者提供一个小于运算符:

struct MyStruct_Compare {
    bool operator()(const MyStruct& a, const MyStruct& b) {
        return a.distance < b.distance;
    }
}
std::sort(mystruct.begin(), mystruct.end(), MyStruct_Compare());

或:

bool operator<(const MyStruct& a, const MyStruct& b) {
    return a.distance < b.distance;
}
std::sort(mystruct.begin(), mystruct.end());