c++ - std::set<键、比较器、分配器>

标签 c++ set stdset

我最近尝试使用 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/

相关文章:

c++ - 如何在不使用 std::vectors 的情况下使用运算符 -= 从动态分配的对象数组中删除元素?

c++ - 如何在客户端-服务器模型(OpenCV C++)中通过套接字传输 cv::VideoCapture 帧?

相当于Rust枚举的C++

search - Fortran:集合操作

c++ - 如何从存储在std::map中的std::set中删除元素?

c++ - 如何在仍然允许 ADL 等的情况下调用同名的其他函数

c - 帕斯卡 - 集合如何工作?

java - 修改反射(reflect)在本地引用中的类级别 HashMap 更改

c++ - 获取 std::set 子集的有效方法

c++ - std::set of std::string 不等式实现