2015-12-01 78 views
1

我有很多Rect rectanglevector<Rect>。但它裏面有許多重複的矩形。如何刪除它們?例如:如何從矢量<Rect>中刪除重複的矩形?

Point Pt1(267, 83);     
    Point Pt2(487, 167); 
    Rect rec1(Pt1, Pt2); 
    GroundTruthSet.push_back(rec1); 


    Point Pt3(257, 90); 
    Point Pt4(450, 150); 
    Rect rec2(Pt3, Pt4); 
    GroundTruthSet.push_back(rec2); 

    Point Pt5(267, 83);     
    Point Pt6(487, 167); 
    Rect rec3(Pt1, Pt2); 
    GroundTruthSet.push_back(rec3); 

如何刪除重複矩形vector<Rect>

+1

它們儲存在一組,然後再複製到矢量? – Borgleader

+12

std :: sort + std :: unique + erase –

+1

http://en.cppreference.com/w/cpp/algorithm/unique。 –

回答

2

您需要在Rect上創建一個Strict Weak Ordering。對於矩形,比較它們各自的組件就足夠了。

auto comp_lt = [](const Rect& lhs, const Rect& rhs) { 
    // compare each component in the following lexicographical order 
    return std::tie(lhs.x, lhs.y, lhs.width, lhs.height) < 
     std::tie(rhs.x, rhs.y, rhs.width, rhs.height); 
}; 
auto comp_eq = [](const Rect& lhs, const Rect& rhs) { 
    // `std::unique` uses equality-comparison, not less-than-comparison 
    return std::tie(lhs.x, lhs.y, lhs.width, lhs.height) == 
     std::tie(rhs.x, rhs.y, rhs.width, rhs.height); 
}; 

std::sort(std::begin(GroundTruthSet), std::end(GroundTruthSet), comp_lt); 
auto pivot = std::unique(std::begin(GroundTruthSet), std::end(GroundTruthSet), comp_eq); 
v.erase(pivot, std::end(GroundTruthSet)); 

std::sortstd::uniquestd::tie

+3

您可以使用['std :: tie'](http ://en.cppreference.com/w/cpp/utility/tuple/tie)讓比較變得不那麼難看。 – nwp

+0

由於問題標籤opencv3,您可以將'(y1,y2,x1,x2)'更改爲'(x,y,width,height)':http://docs.opencv.org/3.0-beta/modules/ core/doc/basic_structures.html#rect – ilent2

+0

@ilent謝謝,只需設置它即可 –