2012-07-07 78 views
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()); 

然后将很好地工作。

+1

定义一个比较函数,然后使用'std :: sort'。见例如这里:http://cplusplus.com/reference/algorithm/sort/。 – 2012-07-07 14:03:09

+0

可能的重复http://stackoverflow.com/questions/1380463/sorting-a-vector-of-custom-objects – jogojapan 2012-07-07 15:17:38

+0

[按对象的属性排序对象向量](http:// stackoverflow。 com/questions/5174115 /通过对象属性排序对象) – ildjarn 2012-07-07 15:39:22

回答

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

+5

这很有效,很清楚。不过,我建议在使用'operator <'之前一个犹豫,除非明确说明一个'MyStruct'是“小于”另一个。如果没有意义,那么使用命名比较器函数可能会更清楚。我想这在OP的例子中可能就是这种情况。 – 2012-07-07 14:15:21

+0

@OliCharlesworth - 你说什么,真的很有意义。我从来没有想过,**好评**! :) – 2012-07-07 14:22:17

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()); 

OR:

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

std::sort(mystruct.begin(), mystruct.end()); 
相关问题