Reference as key in std::map

后端 未结 4 693
傲寒
傲寒 2021-02-07 12:39

Suppose some data structure:

typedef struct {
    std::string s;
    int i;
} data;

If I use the field data.s as key when adding i

4条回答
  •  灰色年华
    2021-02-07 12:52

    You can't store references in Standard Library containers - your map should look like:

    map  mymap;
    

    The map will manage both the key string and the struct instances, which will be copies, for you. Both map and unordered_map work in the same way in this regard, as do all other Standard Library containers.

    Note that in C++, you don't need typedefs to declare structs:

    struct data {
        std::string s;
        int i;
    };
    

提交回复
热议问题