Using The [] Operator Efficiently With C++ unordered_map

前端 未结 3 754
走了就别回头了
走了就别回头了 2021-01-31 02:42

Firstly could someone clarify whether in C++ the use of the [] operator in conjunction with an unordered_map for lookups wraps a call to the find() method, or is using the [] op

3条回答
  •  渐次进展
    2021-01-31 03:36

    You can both check if an element exists, and insert a new element if it does not exist, with the special insert function that returns a pair in which the boolean value tells you if the value has been actually inserted. For example, the code here:

      unordered_map mymap;
      pair::iterator,bool> ret;
    
      // first insert function version (single parameter):;
      mymap.insert ( pair('z',200) );
      ret=mymap.insert (pair('z',500) ); 
      if (ret.second==false)
      {
        cout << "element 'z' already existed";
        cout << " with a value of " << ret.first->second << endl;
      }
    

    The code here inserts the pair <'z',200> into the map if it does not exist. It returns the iterator where it is inserted if the value of the second element of the pair returned is true, or, it returns the iterator where the element actually was, if the second element of the pair is false.

提交回复
热议问题