简体   繁体   中英

C++: Searching a std::set of pointers to class

I asked a rather poorly formulated (and duly poorly received, whoops) question similar to this yesterday that I've had time to think about and better explain (and I also made some progress in attempting to figure out the issue), so here goes:

I have a class State and a class Node . Node contains a pointer to a State as a member:

class State{
public:
    int a;
    int b;
    State(int a1, int b1){
        a = a1;
        b = b1;
    }
};

class Node{
public:
    State *s;
    Node(State *s1){
        s = s1;
    }
    Node(){
        s = NULL;
    }
};

int main() {
    State *s = new State(5, 6);
    State *z = new State(5, 6);
    Node *n = new Node(s);
    set<State*> states;
    states.insert(s);
    cout<<states.count(z);
    return 0;
}

You can see in main that I'm creating two identical pointers to State , inserting one into the set, and then using state::count (returns 1 for found, 0 for not found) to look for a State identical to z in states . This should return 1, but it returns 0. I thought at first this was because I needed to overload the comparator between States , but even after writing this function:

bool operator==(const State &s1, const State &s2){
    if(s1.a == s2.a && s1.b == s2.b)
        return true;
    else
        return false;
}

I'm returning 0. My next idea was because this was a set of pointers to State rather than the actual objects, and because of that my == overload was being bypassed. So I tried this:

int main() {
    State *s = new State(5, 6);
    State *z = new State(5, 6);
    Node *n = new Node(s);
    set<State> states;
    states.insert(*s);
    cout<<states.count(*z);
    return 0;
}

There's a running example of this here: http://ideone.com/iYQyBK

My idea was to have a set of State rather than pointers to State and then dereference the pointers to pass in, but unfortunately this new code gives me all sorts of ugly compilation errors which are very obscure and seem to have something to do with a failure during comparison, but I can't really tell what they mean. What's my best move here to get set::count to work properly (or to find some other way to check if a State is in my set )?

std::set requires strict ordering:

bool operator<(const State &lhs, const State &rhs){
    return std::tie(lhs.a, lhs.b) < std::tie(rhs.a, rhs.b);
}

And then

int main() {
    State s(5, 6);
    State z(5, 6);
    Node n(&s);
    std::set<State> states;
    states.insert(s);
    std::cout << states.count(z);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM