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

时间:2012-07-07 14:01:16

标签: c++

我想用距离变量对“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());

然后将完美地运作。

2 个答案:

答案 0 :(得分:6)

您需要为您的结构编写自己的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<更容易(初学者)

答案 1 :(得分:5)

您需要为sort函数提供一个仿函数,或者为less运算符提供:

struct MyStruct_Compare {
    bool operator()(const MyStruct& a, const MyStruct& b) {
        return a.distance < b.distance;
    }
}

std::sort(mystruct.begin(), mystruct.end(), MyStruct_Compare());

OR:

bool operator<(const MyStruct& a, const MyStruct& b) {
    return a.distance < b.distance;
}

std::sort(mystruct.begin(), mystruct.end());