Is it correct to use map:insert() or []?

Asked 2 years ago, Updated 2 years ago, 104 views

When adding data to the map

I know there are two ways, but I want to know the difference between the two and which one is right (standard?).

c++ map stl

2022-09-21 21:26

1 Answers

For map[key] = value;, there is no way to determine if the value corresponding to key is newly created or if the existing value has changed.

map::insert() can distinguish the two, and the usage is as follows

int main ()
{
  std::map<char,int> mymap;

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

  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';
  }
}

Code source: std:map::insert


2022-09-21 21:26

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.