代码之家  ›  专栏  ›  技术社区  ›  Ruan Kotovich

std::设置<键、比较器、分配器>

  •  0
  • Ruan Kotovich  · 技术社区  · 7 年前

    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';
          }
        }
    

    如何保持位置较小的节点的顺序,但不包括equals引用?

    2 回复  |  直到 7 年前
        1
  •  3
  •   Tobias Ribizel    7 年前

    这不能用单一的方法来实现 std::set

    set.emplace 插入或不插入元素,但不会替换现有元素,请参见 the documentation

    最好的解决方案可能是使用 std::map<int, int> position reference 如果值变小,则更新该值,或者继续使用 标准::设置 参考 更小

    < != )

        2
  •  1
  •   Richard Hodges    7 年前
    #include <iostream>
    #include <set>
    
    struct Node {
        int position;
        int reference;
    
        Node(int r, int p)
                : position(p), reference(r) {
        }
    };
    
    
    struct NodeSet {
        struct AscendingReference {
            bool operator()(const Node &n1, const Node &n2) const {
                return n1.reference < n2.reference;
            }
        };
    
        struct SmallerPosition {
            bool operator()(const Node &n1, const Node &n2) const {
                return n1.position < n2.position;
            }
        };
    
        using Storage = std::set<Node, AscendingReference>;
    
        auto &propose(Node n) {
            auto ifind = storage_.find(n);
            if (ifind != std::end(storage_)) {
                if (not SmallerPosition()(n, *ifind))
                    return *ifind;
                storage_.erase(ifind);
            }
            return *(storage_.insert(std::move(n)).first);
        }
    
        auto begin() const { return storage_.begin(); }
    
        auto end() const { return storage_.end(); }
    
    private:
        Storage storage_;
    };
    
    
    int main() {
        NodeSet aNodes;
    
        aNodes.propose(Node(1, 1));
        aNodes.propose(Node(1, 2));
        aNodes.propose(Node(1, 0));
    
        for (auto nd : aNodes) {
            std::cout << nd.reference << ' ' << nd.position << '\n';
        }
    }