Do STL maps initialize primitive types on insert?

前端 未结 4 606
眼角桃花
眼角桃花 2020-12-05 06:25

I have a std::map like this:

map Scores;

It stores names of players and scores. When someone gets a score I

4条回答
  •  难免孤独
    2020-12-05 06:51

    You should not test if the item exists before incrementing it. The [] operator does exactly what you need it to do, as others have said.

    But what if the default-constructed value wouldn't work for you? In your case the best way to find if the element already exists is to try to insert it. The insert member function for std::map returns a std::pair. Whether the insert succeeds or fails, the first element of the pair will point to the desired object (either your new one, or the one that was already present). You can then alter its value as you see fit.

提交回复
热议问题