指定对象属性的唯一矢量对象

时间:2011-03-23 05:38:17

标签: c++ vector unique

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

如果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

2 个答案:

答案 0 :(得分:0)

如果您不需要维护元素的顺序,则应将元素插入sethash_set(取决于元素的数量)并创建比较和/或散列函数告诉(hash_)set具有相同.y属性的对象是“相等的”。

答案 1 :(得分: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());
}