STL MAP should use find() or [n] identifier to find element in map?

前端 未结 4 1602
离开以前
离开以前 2020-12-05 20:37

I am confused which is more efficient?

As we can access map directly, why do we need to use find?

I just need to know which way is more efficient.



        
4条回答
  •  执笔经年
    2020-12-05 21:26

    Using find means that you don't inadvertently create a new element in the map if the key doesn't exist, and -- more importantly -- this means that you can use find to look up an element if all you have is a constant reference to the map.

    That of course means that you should check the return value of find. Typically it goes like this:

    void somewhere(const std::map & mymap, K const & key)
    {
        auto it = mymap.find(key);
        if (it == mymap.end()) { /* not found! */ }
        else                   { do_something_with(it->second); }
    }
    

提交回复
热议问题