How to have a set of structs in C++

前端 未结 7 498
渐次进展
渐次进展 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:00

    The best thing to do is to give foo a constructor:

    struct foo
    {
        foo(int k) : key(k) { }
        int key;
    };
    

    Then to add, rather than...

    foo *test = new foo;
    test->key = 0;
    bar.insert(test);   // BROKEN - need to dereference ala *test
    // WARNING: need to delete foo sometime...
    

    ...you can simply use:

    bar.insert(foo(0));
    

提交回复
热议问题