D
D
Daniel2018-10-14 23:54:09
C++ / C#
Daniel, 2018-10-14 23:54:09

C++ how to add elements to hash_map?

Need to add keys to the hash_map, but at least something?
Questions, where to get the documentation. On the documentation site, the example does not plow, there https://msdn.microsoft.com/ru-ru/library/0d462wfh.aspx

hash_map<std::string, list<Listener*>> * listeners;
/// и есть такой конструктор 

EventManager::EventManager(list<std::string>* eventsType){
     typedef pair<std::string, std::list<Listener*>> mapData;
     for (auto  iter = eventsType->begin(); iter != eventsType->end(); iter++) {
    list<Listener*> a;
    this->listeners->insert(mapData(*iter,a)); // все фегня все не работает
  }

}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman, 2018-10-15
@myjcom

#include <iostream>
#include <memory>
#include <unordered_map>
#include <list>

struct Listener
{
  std::string _name;
  Listener(std::string name) : _name{ name }{}
  ~Listener() = default;
};

using Listeners = std::unordered_map<std::string, std::list<Listener>>;

class EventManager
{
public:
  EventManager(std::list<std::string>& eventTypes);
  //...
  ~EventManager() = default;
  void print()
  {
    for(const auto& v : *m_listeners)
    {
      std::cout << v.first << " -> ";
      for(const auto& s : v.second)
      {
        std::cout << s._name << ' ';
      }
      std::cout << std::endl;
    }
  }
private:
  std::unique_ptr<Listeners> m_listeners;
};

EventManager::EventManager(std::list<std::string>& eventTypes)
                          : m_listeners { std::make_unique<Listeners>() }
{
  auto insert_it(std::end( *m_listeners ));
  for (const auto &et : eventTypes)
  {
    insert_it = m_listeners->insert( insert_it, {et, {}} );
  }
}

int main()
{
  std::list<std::string> events { "Open", "Move", "Close" };
  EventManager eManager{ events };
  eManager.print();
}

It is also desirable to write your own hash function .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question