What is wrong in this program
Mar 18, 2016 at 4:30am UTC
I am getting this error "no matching function for call to 'make_pair(char&, int)'" when I am trying to insert into hash map(using make_pair) as shown in the below code. Can some one tell me what I am doing wrong?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <unordered_map>
#include <utility>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
unordered_map<char ,int > hash_map;
vector<int > freq;
string str;
int len,count=0;
cin >> str;
len = str.length();
//storing str occurrence in hash map
for (int i=0; i<len; i++){
auto itr = hash_map.find(str[i]);
if ( itr == hash_map.end()){
hash_map.insert(std::make_pair<char ,int >(str[i],1));
}
else {
itr->second = itr->second + 1 ;
}
}
Mar 18, 2016 at 4:51am UTC
Try casting
hash_map.insert(std::make_pair<char ,int >(static_cast <char >(str[i]),1));
Mar 18, 2016 at 5:09am UTC
The raison d'ĂȘtre for
std::make_pair is to let it deduce the target types correctly.
1 2
// hash_map.insert(std::make_pair<char,int>(str[i],1));
hash_map.insert( std::make_pair( str[i], 1 ) ) ; // types deduced as char, int
Or, with C++11, either one of these:
1 2
hash_map.insert( { str[i], 1 } );
hash_map.emplace( str[i], 1 );
Topic archived. No new replies allowed.