我最近尝试使用 set 将一些配置保存在 trie
中。
我在比较器上发现了一个疑问,例如:
#include <iostream>
#include <set>
using namespace std;
struct Node{
int position;
int reference;
Node(int r, int p){
this->position = p;
this->reference = r;
}
};
struct Node_c{
const bool operator()(const Node& n1, const Node& n2){
// return n1.reference != n2.reference;
// i've tried some functions here, like n1.reference != n2.reference ? true : n1.position < n2.position;
}
};
int main(){
set<Node, Node_c> aNodes;
aNodes.emplace(1,1);
aNodes.emplace(1, 2); // i dont want to add this one, the reference already exists and the position is bigger than the last one
aNodes.emplace(1, 0); // i want to replace the (1,1) for this one
for(auto nd : aNodes){
cout << nd.reference << ' ' << nd.position << '\n';
}
}
我怎样才能让位置较小的节点按顺序排列,但不包括等于引用?
谢谢。
最佳答案
这不能通过 std::set
的单一方法完成,因为它严格要求其元素具有唯一键!
set.emplace
要么插入一个元素,要么不插入,但它不会替换现有元素,请参阅 the documentation
对您来说最好的解决方案可能是使用 std::map<int, int>
其中一个 position
映射到 reference
并在值变小时更新该值,或者继续使用 std::set
并编写一个自定义方法,首先检查该集合是否包含一个元素,如果是,则仅在新的 reference
时才替换它。比较小
此外,您的比较器应该比较小于 (<
),而不是不等式 (!=
)
关于c++ - std::set<键、比较器、分配器>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44980064/