2011-03-23 74 views
1

获取具有唯一指定对象属性的矢量(不是唯一对象只是具有唯一指定属性的对象)的最有效方法是什么?指定对象属性的唯一矢量对象

若y需要的是一个独特的属性

point.x = 2 point.y = 3 
point.x = 3 point.y = 3 
point.x = 4 point.y = 4 
point.x = 4 point.y = 5 

将变成:

point.x = 3 point.y = 3 
point.x = 4 point.y = 4 
point.x = 4 point.y = 5 

回答

0

一种方法是这样的:

struct Point 
{ 
    Point(int x_in,int y_in): x(x_in), y(y_in){} 
    int x; 
    int y; 
}; 


int main() 
{ 
    using namespace boost::lambda; 
    using namespace std; 

    vector<Point> v; 
    v.push_back(Point(2,3)); 
    v.push_back(Point(3,3)); 
    v.push_back(Point(4,4)); 
    v.push_back(Point(4,5)); 

    //First sort the vector as std::unique requires a sorted range 
    stable_sort(v.begin(), v.end(), bind(&Point::y, _1) < bind(&Point::y, _2)); 

    //Make the elements in the vector unique and erase the duplicate elements from the vector 
    v.erase(unique(v.begin(),v.end(), bind(&Point::y, _1) == bind(&Point::y, _2)), v.end()); 
} 
0

如果您不需要维护元素的顺序,你应该将您的内容纳入一个sethash_set(取决于元素的数量)并创建比较和/或散列函数来告诉(hash_)set具有相同.y属性的对象是“相等的”。要做到这一点

+0

你可能想unordered_set而非的hash_set,因为前者更规范。 – templatetypedef 2011-03-23 05:47:10