Hashmap in c++

I am passing a string array and an empty map as input;
if the element in array is in map, it should increase the value of index in map else it should just add the key and index into map.

#include <iostream>
#include <map>
#include <iterator>
using namespace std;

int main()
{
string array[5]={"val","nir","sas","nir","val"};
map<string,int> mapone={};
map<string,int>::iterator itr;
string check;
int i;

for(i=0;i<5;i++)
{
cout<<array[i]<<" ";
if(mapone.find(array[i]))
{
check=array[i];
check->second = check->second + 1;
}
else
{
mapone.insert(pair<string,int>(array[i],1));
}
}

for(itr=mapone.begin();itr!=mapone.end();itr++)
{
cout<<itr->first;
cout<<" ";
cout<<itr->second;
cout<<" ";
cout<<"\n";
}
cout<<"done";

return 0;
}

Output which i expect:


val 2
nir 2
sas 1

But I am having error in find function. Can anyone point out why i am not able to do it. Would be helpful.
Thanks
Last edited on
mapone.find(array[i]) returns the iterator map<string,int>::iterator which is not convertible to bool, hence the if expression cannot compile. Try
1
2
3
4
5
for(i=0;i<5;i++)
{
cout<<array[i]<<" ";
++(mapone[array[i]])
}


And check is a string without a member second
Last edited on
Topic archived. No new replies allowed.