2017-09-23 50 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