Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the difference between using insert function when using std::map.insert("xyz") or just map[ind]="xyz"

In the following example what is the pros and cons of using 1) versus 2). Is there any memory allocation benefits, any benefits as far as not running out of space?

map <  int, string> Employees;  



  // 1) Assignment using array index notation  

   Employees[5234] = "Mike C.";  

  // 2) Assignment using member function insert() and STL pair  

    Employees.insert(std::pair<int, * char>(1923,"David D."));  
like image 387
user553514 Avatar asked Dec 06 '22 23:12

user553514


1 Answers

The first creates a mapping with key 5234 and returns a reference to the string held there, to which "Mike C" gets assigned - important point is, if the key already exists, this will overwrite the value at that key (because a reference to the value is returned).

The second approach checks to see if the key is present, and will not overwrite if it does already exist.

As for memory allocation, both will increase the map size by 1 if the mapping does not exist. The above is the only difference between the two approaches AFAIK.

like image 199
Nim Avatar answered Jan 19 '23 00:01

Nim