How to have a set of structs in C++

前端 未结 7 616
渐次进展
渐次进展 2021-02-01 21:01

I have a struct which has a unique key. I want to insert instances of these structs into a set. I know that to do this the < operator has to be overloaded so that set can mak

7条回答
  •  没有蜡笔的小新
    2021-02-01 22:04

    see ereOn's answer, it's right.

    The real problem in you code is this:

    foo *test = new foo;
    test->key = 0;
    bar.insert(test);
    

    You insert a pointer in the set, not a struct. Change the insert to:

     bar.insert( *test );
     //          ^
    

    EDIT: but then you'll need to delete foo, as it will be copied in the set. Or just create it on the stack (using set with pointers is not a good idea, because the arrangement will be "strange" - the set will sort according to the pointers' addresses )

提交回复
热议问题