C++设置唯一和顺序
C++ set unique and order
我想在set<Foo, FooComp>
中做到唯一和有序。
在下面的代码中,我想要 a 唯一并按 b 和 c 排序。 因此,没有相同的foo.a
和foo.b
和foo.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 });
}
相关文章:
- CMake-按正确顺序将项目与C运行时对象文件链接
- 函数调用中参数的顺序重要吗
- 为什么不;名字在地图上是按顺序排列的吗
- 何时在引用或唯一指针上使用移动语义
- 将Integer转换为4字节的unsined字符矢量(按大端字节顺序)
- 数到第n个楼梯的路(顺序无关紧要)
- C++优先级队列,按对象的唯一指针的特定方法升序排列
- 计算排序向量的向量中唯一值的计数
- 优先顺序:智能指针和类析构函数
- 如何使用Visual Studio 2017在C++中为参数化对象数组使用唯一指针
- 在循环中按顺序遍历成员变量
- 独立读取-修改-写入顺序
- QML按钮点击功能执行顺序
- 从数组中删除非唯一值、保持顺序和不使用向量的最佳方法?
- 将fetch_add与宽松的内存顺序返回唯一值
- 如何使用 std::shuffle 以随机顺序对具有唯一指针的向量进行洗牌
- 是否有可以将每个双精度转换为唯一uint64_t,保持精度和顺序的功能?(为什么我找不到?
- C++设置唯一和顺序
- c++需要字符串的唯一ID,但无论顺序如何都必须相同
- 找到一个共同的唯一的顺序