2017-09-23 53 views
0

我想在set<Foo, FooComp>中進行唯一和訂購。C++設置唯一和訂單

在下面的代碼中,我想要一個唯一的,並按b和c排序。 所以,沒有相同的foo.a和訂購foo.bfoo.c

我該怎麼做?

struct Foo { 
    int a, b, c; 
    Foo(int a, int b, int c) : a(a), b(b), c(c) {} 
} 

struct FooComp { 
    bool operator() (const Foo& f, const Foo& s) const { 
     if (f.pattern == s.pattern) { 
      return false; 
     } 
     if (f.start == s.start) { 
      return f.length < s.length; 
     } 
     return f.start < s.start; 
    } 
} 

還是我使用其他的STL或數據結構?

+0

,我想使用的地圖,'了'關鍵和'(B,C)'的值。但是,地圖不是爲這種情況設計的(我認爲)。 – Maybe

回答

0

這不可能使用標準庫集。

比較運算符與排序緊密結合。

雖然在性能方面有點差的解決方案,你可以有一組包含所有對象,排序「一」只使用:

struct Foo { 
    int a, b, c; 
    Foo(int a, int b, int c) : a(a), b(b), c(c) {} 
    bool operator<(const Foo& rhs) const { 
     return a < rhs.a; 
    } 
    friend ostream& operator<<(ostream&, const Foo&); 
}; 

然後,每當你想使用對它進行排序你的獨特的算法,只需將它複製到一個載體和排序它根據你的需要:

vector<Foo> v; 
std::copy(s.begin(), s.end(), std::back_inserter(v)); 
std::sort(v.begin(), v.end(), [](const Foo& lhs, const Foo& rhs){ return (lhs.b == rhs.b) ? lhs.c > rhs.c : lhs.b > rhs.b; }); 

編輯

這實現了您在Pastebin示例中使用的邏輯。 整個樣本here

+0

這不符合我的想法。 在此代碼(https://pastebin.com/dCBpcQB2),我期望 1,2,3 2,3,1 3,5,2 但結果是 1,2,3 2, 3,1 3,5,2 1,5,7 – Maybe

+0

@也許,我更新了我的答案 –

+0

,我知道這個答案,但這是最好的答案?我不確定... – Maybe

0

有一個現成的庫,這種類型的東西在boost稱爲boost.multi_index。

它允許聲明滿足多個索引及其約束的容器。

這有點古老,可以做一些愛,但它做的工作。

你可以像這樣開始:

struct Foo { 
    int a, b, c; 
    Foo(int a, int b, int c) : a(a), b(b), c(c) {} 
}; 

#include <tuple> 
#include <type_traits> 
#include <utility> 
#include <boost/multi_index_container.hpp> 
#include <boost/multi_index/member.hpp> 
#include <boost/multi_index/ordered_index.hpp> 


struct get_a 
{ 
    using result_type = int const&; 
    result_type operator()(Foo const& l) const { 
     return l.a; 
    } 
}; 

struct get_bc 
{ 
    using result_type = std::tuple<int const&, int const&>; 

    result_type operator()(Foo const& l) const { 
     return std::tie(l.b, l.c); 
    } 
}; 

namespace foo { 
    using namespace boost; 
    using namespace boost::multi_index; 

    struct by_a {}; 
    struct by_bc {}; 

    using FooContainer = 
multi_index_container 
< 
    Foo, 
    indexed_by 
    < 
     ordered_unique<tag<by_a>, get_a>, 
     ordered_non_unique<tag<by_bc>, get_bc> 
    > 
>; 
} 

int main() 
{ 
    foo::FooContainer foos; 

    foos.insert(Foo{ 1, 2,3 }); 
    foos.insert(Foo{ 2, 2,4 }); 

} 
+0

哇,非常感謝,但是提高圖書館是不允許我的環境的。 – Maybe