Jump to content
  • Advertisement
Sign in to follow this  

Help to understand my own misstake?

This topic is 2017 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts


Today/Yesterday I been having a few problem in my code which I manged to "solve", but I was wondering why my original approach didnt work? 

Basically I have this std::map with a vector inside it like

std::map<int, std::vector<GameObject*>> testMap;

than i started to insert stuffs like so

mapTest.insert(std::pair<int, std::vector<GameObject*>>(renderID,{gameObjectTest})); //first try
mapTest.insert(mapTest.end(),std::pair<int, std::vector<GameObject*>>(renderID,{gameObjectTest})); //second try

I also tried to have a tempVector where I push_back the gameObjectTest in it and just had tempVector instead of { gameObjectTest } 


At this point I got no syntax error or the likes, and when I ran the code it works great.

But when I tried to access the gameobject via 


I get a std::out_of_range error,

but instead of using .at I tried to use

std::map<int, std::vector<GameObject*>>::iterator it = mapTest.begin();

for now it works and I get no std::out_of_range error. I was wondering how come .at doesnt work but .begin (aka iterator) works?

Edited by Conny14156

Share this post

Link to post
Share on other sites



std::map::at takes a key, not an index. What your first try was actually accomplishing was returning the value associated with key=0. In the words of that reference:


std::out_of_range if the container does not have an element with the specified key


You didn't have key=0 in your std::map hence that exception. std::map::begin, however, returns an iterator to the first std::pair in the std::map container. The key isn't used at all. As long as there is one item in your std::map the iterator method will work.

Share this post

Link to post
Share on other sites

Unless you can guarantee that the particular key you want is in the map you may instead want to consider using find and checking the returned iterator is valid.

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!