1

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

然后将完美地工作。

4

2 回答 2

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<更容易(对于初学者)

于 2012-07-07T14:02:41.493 回答
5

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

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());
于 2012-07-07T14:04:59.010 回答