Reference as key in std::map

后端 未结 4 694
傲寒
傲寒 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 <string,data> 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;
    };
    
    0 讨论(0)
  • 2021-02-07 12:53

    I don't think there's a big performance gain if you choose pointer instead of object. Only do this if you're managing data with lot of existing string objects which need to hold inside the container. Also the destruction of the objects has to be managed manually before destructing the container.

    0 讨论(0)
  • 2021-02-07 13:06

    C++11

    Since C++11 reference wrapper is part of standard.

    #include <functional> 
    
    std::map<std::reference_wrapper<std::string>, data>
    

    Using Boost

    You may want to take a look at boost.ref. It provides a wrapper that enables references to be used in STL-containers like this:

    std::map<boost::reference_wrapper<std::string>, data>
    
    0 讨论(0)
  • 2021-02-07 13:16

    You cannot use the reference. The map can copy the content. This is I guess implementation dependent.

    But tested with the microsoft STL.

    struct data
    {
                data(data const& rhs)
                {
                   a new object will be created here
                }
                std::string s;
                int i; 
    };
    

    Add some objects to the map and you will run into the copy constructor. This should invalidate your reference.

    0 讨论(0)
提交回复
热议问题