1. 程式人生 > >c++ -- map的insert及[]兩種元素插入方式比較

c++ -- map的insert及[]兩種元素插入方式比較

首先需要明確的是:map中不允許存在相同的key 

對於c++中map容器,可以使用insert或者[]操作插入元素,這兩個方式有什麼區別了?下面分別從功能,效率,安全性等方面進行分析

1 insert方式

Because element keys in a map are unique, the insertion operation checks whether each inserted element has a key equivalent to the one of an element already in the container, and if so, the element is not inserted, returning an iterator to this existing element (if the function returns a value).

  std::map<char,int> mymap;

  // first insert function version (single parameter):
  mymap.insert ( std::pair<char,int>('a',100) );  // std::pair
  mymap.insert ( std::make_pair('z',200) );       // std::make_pair

  std::pair<std::map<char,int>::iterator,bool> ret;
  ret = mymap.insert ( std::pair<char,int>('z',500) );
  if (ret.second==false) {
    std::cout << "element 'z' already existed";
    std::cout << " with a value of " << ret.first->second << '\n';
  }

The single element versions (1) return a pair, with its member pair::first set to an iterator pointing to either the newly inserted element or to the element with an equivalent key in the map. The pair::second element in the pair is set to true if a new element was inserted or false if an equivalent key already existed.