Reputation: 11
Here it is using the unordered_map
for the hashtable concept but I am not sure how it is doing so without even inserting item into the key value pair of undered_map
.
This is the code for finding the pairs within an unsorted array. Here it is using hashtable concept for everyother element.
void findPair(int arr[],int n,int x)
{
unordered_map<int,int> umap;
for(int i=0;i<n;i++)
{
int temp=x-arr[i];
if(umap.find(temp)!=umap.end())
{
int count=umap[temp];
for(int j=0;j<count;j++)
cout<<arr[i]<<" "<<temp<<"\n";
}
umap[arr[i]]++;
}
}
Can you please give me some insight how it is inserting and why it is incrementing the count of that value?
Upvotes: 0
Views: 108
Reputation: 10750
The map counts the number of times each element occurs in the unsorted array. By default, if you write
umap[key]
and key
is not in umap
, it inserts key
into umap
with a default value of 0
. It then returns a reference to the location where the key was stored in the map.
This means that for a new key given by arr[i]
, the key is inserted into the map when you call umap[arr[i]]
, and then that value is incremented so that the map registers a count of 1
for that key.
Upvotes: 1