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

前端 未结 4 1626
离开以前
离开以前 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:27

    This code and doc is picked from cplusplus.com

    // accessing mapped values
    #include 
    #include 
    #include 
    using namespace std;
    
    int main ()
    {
      map mymap;
    
      mymap['a']="an element";
      mymap['b']="another element";
      mymap['c']=mymap['b'];
    
      cout << "mymap['a'] is " << mymap['a'] << endl;
      cout << "mymap['b'] is " << mymap['b'] << endl;
      cout << "mymap['c'] is " << mymap['c'] << endl;
      cout << "mymap['d'] is " << mymap['d'] << endl;
    
      cout << "mymap now contains " << (int) mymap.size() << " elements." << endl;
    
      return 0;
    }
    
    OP:
    mymap['a'] is an element
    mymap['b'] is another element
    mymap['c'] is another element
    mymap['d'] is
    mymap now contains 4 elements.
    

    Notice how the last access (to element 'd') inserts a new element in the map with that key and initialized to its default value (an empty string) even though it is accessed only to retrieve its value. Member function map::find does not produce this effect.

提交回复
热议问题