C++设置唯一和顺序

C++ set unique and order

本文关键字:顺序 唯一 设置 C++      更新时间:2023-10-16

我想在set<Foo, FooComp>中做到唯一和有序。

在下面的代码中,我想要 a 唯一并按 b 和 c 排序。 因此,没有相同的foo.afoo.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 或数据结构?

使用标准库集无法做到这一点。

比较运算符与排序紧密耦合。

虽然在性能方面有点差,但你可以有一个包含所有对象的集合,仅使用以下命令按"a"排序:

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 示例中使用的逻辑。 整个示例在这里

在 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 });
}