2011-03-23 79 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