Note that there are some explanatory texts on larger screens.

plurals
  1. POunordered_map of vectors resetting vectors
    text
    copied!<p>I am trying to build a class to handle key callbacks.</p> <p>To do this I have a map defined as so:</p> <pre><code>class Keyboard { public: void registerCallback(int key, callback_fn func, bool repeat = false); void onKeyEvent(int key, int state); private: typedef std::function&lt;void (int)&gt; callback_fn; struct Callback { Callback(callback_fn f, bool r) : func(f), repeat(r), last_state(-1) {} callback_fn func; bool repeat; int last_state; }; std::unordered_map&lt;int, std::vector&lt;Callback&gt;&gt; callbacks; }; </code></pre> <p>I then register callbacks like so:</p> <pre><code>void Keyboard::registerCallback(int key, callback_fn func, bool repeat) { // My understanding is that if there is nothing mapped to the key // it will create a new vector. Otherwise it will return the mapped // object. I did try checking if anything already exists at the key // and if not creating a new vector but it yielded the same results. callbacks[key].push_back({ func, repeat }); } </code></pre> <p>However I am having an issue where the mapped vector appears to lose all of it's elements.</p> <p>When I register a callback the vector at the given key increases in size but when I try to iterate over the vector in another method, it has no elements.</p> <p>Below is how my method for iterating over the vector.</p> <pre><code>void Keyboard::onKeyEvent(int key, int state) { for(auto&amp; callback : callbacks[key]) { if(callback.repeat || callback.last_state != state) { callback.func(state); } } } </code></pre> <p>Note if I add <code>std::cout &lt;&lt; callbacks[key].size() &lt;&lt; std::endl;</code> to the top of the function it prints <code>0</code>.</p> <p>If it matters here is an example of how I register a callback.</p> <pre><code>keyboard.registerCallback('w', [](int state) { std::cout &lt;&lt; "w " &lt;&lt; (state == GLFW_PRESS ? "pressed" : "released") &lt;&lt; std::endl; }, true); </code></pre> <p>I suspect my problem stems from differences between Java's maps, which I am more used to, and C++'s maps</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload