C++ 从指针集中擦除不起作用?

问题描述 投票:0回答:1

我创建了一组指针,并尝试在以下代码中删除一个成员:

#include <iostream>
#include <set>

using namespace std;

struct Node{
    Node(int val){
        this->val = val;
    }
    int val;
    Node* prev;
    Node* next;
};

struct comp{
    bool operator()(const Node* a, const Node* b) const{
        a->val<=b->val;
    }
};

int main() {
    set<Node*, comp> s;
    Node* n1 = new Node(1);
    s.insert(n1);
    Node* n2 = new Node(2);
    s.insert(n2);
    Node* n3 = new Node(1);
    s.insert(n3);
    
    for(auto it=s.begin();it!=s.end();it++){
        cout<<(*it)->val<<",";
    }
    cout<<endl;

//print out 1, 1, 2
    
    s.erase(n1);
    
    for(auto it=s.begin();it!=s.end();it++){
        cout<<(*it)->val<<",";
    }
    cout<<endl;

//still print out 1, 1, 2 after deleting n1

    return 0;
}

好像把指针擦掉后,打印结果还是显示的。有人可以帮我解释一下吗?如果我想从集合中删除指针,正确的方法是什么?

c++ pointers stl
1个回答
0
投票

您的 comp 函子不满足

[Compare][1]
要求

struct comp{
    bool operator()(const Node* a, const Node* b) const{
        a->val<=b->val;
    }
};

比较是一些标准预期的一组要求 来自用户提供的函数对象类型的库设施。

应用于对象的函数调用操作的返回值 满足 Compare 的类型,当上下文转换为 bool 时, 如果调用的第一个参数出现在 在这种类型引发的严格弱排序关系中第二个,并且 否则为假。

© www.soinside.com 2019 - 2024. All rights reserved.