Unable to use map,unordered_map and pair for some reason


#1

Can somebody explain why I’m getting a runtime error on using maps,unordered_map or pair. The compiler is not allowing it for some reason.


#2

it uses more memory than alotted


#3

use unordered_set, it gets accepted.


#4

Here is simple C++ solution using unordered_map and pair

bool sortbysec( pair<int,int> &a,
pair<int,int> &b)
{
if(a.first == b.first)
return a.second > b.second;

return (a.first < b.first); 

}
vector Solution::solve(string A, vector &B)
{
unordered_map<string,int> mp;

int n = A.size();
int i = 0;

while(i<n)
{
string p;
while(A[i]!=’_’ and i<n)
{
p.push_back(A[i]);
i++;
}
i++;
mp[p]++;
}

vector<pair<int,int>> ans;
for(int x=0; x<B.size(); x++)
{
n = B[x].size();
string a = B[x];
i =0;
int w =0;
while(i<n)
{
string p;
while(a[i]!=’_’ and i<n)
{
p.push_back(a[i]);
i++;
}
i++;
if(mp.find§!=mp.end())
w++;
}
ans.push_back(make_pair(w,x));
}

sort(ans.begin(),ans.end(),sortbysec);
reverse(ans.begin(),ans.end());

vector s;

for(int x=0; x<B.size(); x++)
{
s.push_back(ans[x].second);
}

return s;
}


#5

Not sure but if you search for some value in the map using (map[value]!=0), if that value is present then its okay otherwise it would assign a memory for that element with default value, hence your map will grow larger and larger with the new values you check by this method. if you are searching using map.find() then this problem should not arise.