How should std::map be used with a value that does not have a default constructor?

前端 未结 3 1700
闹比i
闹比i 2021-01-18 16:58

I\'ve got a value type that I want put into a map. It has a nice default copy constructor, but does not have a default constructor.

I believe that so long as I stay

3条回答
  •  不知归路
    2021-01-18 17:33

    You can simply "insert-or-overwrite" with the standard insert function:

    auto p = mymap.insert(std::make_pair(key, new_value));
    
    if (!p.second) p.first->second = new_value;  // overwrite value if key already exists
    

    If you want to pass the elements by rerference, make the pair explicit:

    insert(std::pair(key, value));
    

    If you have a typedef for the map like map_t, you can say std::pair, or any suitable variation on this theme.


    Maybe this is best wrapped up into a helper:

    template 
    void insert_forcefully(Map & m,
                           typename Map::key_type const & key,
                           typename Map::mapped_type const & value)
    {
      std::pair p = m.insert(std::pair(key, value));
      if (!p.second) { p.first->second = value; }
    }
    

提交回复
热议问题