insert to boost unordered map

房东的猫 提交于 2019-12-23 19:33:05

问题


Hi I'm trying to insert a record into a boost::unordered_map

Map is defined as

boost::unordered_map<int,Input> input_l1_map;

where Input is the class

class Input {

        int id;
        std::string name;
        std::string desc;
        std::string short_name;
        std::string signal_presence;
        std::string xpnt;
        }

I use a function to insert the record as below

void RuntimeData::hash_table(int id,Input input)
{

  this->input_l1_map.insert(id,input);

}

I read the boost documentation it says a function insert() to insert data to the container, but when I compile it shows error.


回答1:


Where you find such insert method?

  std::pair<iterator, bool> insert(value_type const&);
  std::pair<iterator, bool> insert(value_type&&);
  iterator insert(const_iterator, value_type const&);
  iterator insert(const_iterator, value_type&&);
  template<typename InputIterator> void insert(InputIterator, InputIterator);

Where value_type is

  typedef Key                                    key_type;            
  typedef std::pair<Key const, Mapped>           value_type;

from here

You should use this->input_l1_map.insert(std::make_pair(id, input));




回答2:


insert takes a value_type, which is defined as:

typedef std::pair<Key const, Mapped> value_type;

void RuntimeData::hash_table(int id,Input input)
{

  this->input_l1_map.insert(std::make_pair(id,input));

}



回答3:


The most natural way, IMO, to write this would be

input_l1_map[id] = input;

Allthough

input_l1_map.insert({ id,input }); // C++11

would be ok too.

Alternatively, there'll be a typedef for the pairs stored in the map:

typedef boost::unordered_map<int,Input> InputMap;
InputMap input_l1_map;

now you can make it explicit:

InputMap::value_type item(id, input);
input_l1_map.insert(item);


来源:https://stackoverflow.com/questions/15833847/insert-to-boost-unordered-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!