C++ 在 class 中定义集合的顺序
C++ Define an order for a set inside a class
我在 class 中有一个集合,我想为该集合定义一个新顺序,但顺序取决于 class 的属性。我应该如何实施它?
我试过这样的东西
class myclass{
int c;
set<int,cmp> myset;
struct cmp{
bool operator()(const unsint a, const unsint b)
const {
return (depends on c) ;
}
};
}
但是没用。感谢任何帮助,谢谢。
编辑:问题是我不知道 c a priori。这是我输入的值,然后它将始终相同。
return (depends on c) ;
我认为让 comapare 函数依赖于 c
不是个好主意,因为你的 set
对象已经构建树并且 std::set
不支持重建。
此外,请注意 std::set
需要符合 严格弱排序规则 的比较器。
您可以在 'Compare' documentation and wikipedia
阅读更多内容
关于你的问题,你可以用另一个比较函数创建另一个集合,然后将内容复制到这里。
typedef std::set<int, cmp2> anotherSet;
std::copy(std::begin(firstSet), std::end(firstSet), std::inserter(anotherSet));
但是,如果您必须根据某些参数重新排序,看起来您实际上并不需要 std::set
。考虑使用另一种数据结构,如向量或列表。此外,如果您需要 ~O(log N) 访问复杂性,您可以将数据组织到向量中 heap。
我在 class 中有一个集合,我想为该集合定义一个新顺序,但顺序取决于 class 的属性。我应该如何实施它? 我试过这样的东西
class myclass{
int c;
set<int,cmp> myset;
struct cmp{
bool operator()(const unsint a, const unsint b)
const {
return (depends on c) ;
}
};
}
但是没用。感谢任何帮助,谢谢。
编辑:问题是我不知道 c a priori。这是我输入的值,然后它将始终相同。
return (depends on c) ;
我认为让 comapare 函数依赖于 c
不是个好主意,因为你的 set
对象已经构建树并且 std::set
不支持重建。
此外,请注意 std::set
需要符合 严格弱排序规则 的比较器。
您可以在 'Compare' documentation and wikipedia
阅读更多内容关于你的问题,你可以用另一个比较函数创建另一个集合,然后将内容复制到这里。
typedef std::set<int, cmp2> anotherSet;
std::copy(std::begin(firstSet), std::end(firstSet), std::inserter(anotherSet));
但是,如果您必须根据某些参数重新排序,看起来您实际上并不需要 std::set
。考虑使用另一种数据结构,如向量或列表。此外,如果您需要 ~O(log N) 访问复杂性,您可以将数据组织到向量中 heap。