Unordered_map: why doesnt the new key val pair overwrite the old key val pair

why doesnt the new key val pair overwrite the old key val pair??
how can i do it??


int n;
cin>>n;
char a;
string b;
unordered_map<char,string> um;
for(int i=0; i<n; i++)
{
	cin>>a;
	cin>>b;
	um.insert(make_pair(a,b));
}
for(auto p:um)
	cout<<p.first<<","<<p.second<<endl;

input : 2

a apple

a angry


output: a,apple

In an unordered map, all keys must be unique. So it avoids duplicates. It means that 2 key value pair with the same key cannnot be present together. One way to have multtiple values for the same key is by initializing the unordered map as unordered_map<char,list> um; You would have to check here that if the key is already present…then push the new string in the list corresponding to that key.
Also you can modifiy the value of the already present key.
Since the value of um[‘a’] was initiallly as apple…you can change it by um[‘a’]=“angry”

1 Like
    int n;
	cin>>n;
	char a;
	string b;
	unordered_map<char,string> um;
	for(int i=0; i<n; i++)
	{
		cin>>a;
		cin>>b;
		um[a] = b;
	}
	for(auto p:um)
		cout<<p.first<<","<<p.second<<endl;

input: 2
a apple
a angry

output: a,angry

thanks @pratyush63