Reputation: 167
I'm trying to find the most occurrence of char in a dat file. so if there are 24 e's in the file and 8 c's id like it to print out 'e'. I'm getting an error on the " * " of the int max var. The is the error:
Error 3 error C2440: 'initializing' : cannot convert from 'std::pair' to 'int'
ifstream infile(filename);
if (!infile.is_open()) return;
char x;
map<char, int> count;
while (infile >> x) count[x]++;
for (auto it : count)
cout << it.first << " " << it.second << endl;
int max = *max_element(count.begin(), count.end(), count.value_comp());
cout << max << endl;
return ' ';
as always any help is appreciated!
Upvotes: 1
Views: 486
Reputation:
You have two issues
You might change the code to:
#include <algorithm>
#include <iostream>
#include <fstream>
#include <map>
int main() {
std::ifstream infile("filename");
if (!infile.is_open())
return 1; // Check if file opened correctly
char x;
typedef std::map<char, int> map_type;
map_type count;
while (infile >> x) count[x]++;
for (auto it : count) // Pull this out of the while loop
std::cout << it.first << " " << it.second << std::endl;
auto less_count = [] (const map_type::value_type& a, const map_type::value_type& b) {
return a.second < b.second;
};
auto max_pair = std::max_element(count.begin(), count.end(), less_count);
int max = max_pair->second;
std::cout << max << std::endl;
}
Upvotes: 2
Reputation: 44258
When you dereference std::map::iterator
you get std::pair
and you try to assign it to int
. Correct syntax would be:
int max = max_element(count.begin(), count.end(), count.value_comp())->second;
but you should check if there are elements in that map, otherwise you may dereference count.end()
with UB. That would happen if file is empty for example.
Upvotes: 2
Reputation: 511
std::max_element
will return ForwardIterator which in your case will be map<char,int>::iterator
pointing to pair<char,int>
. You have to change the last line to
int max = max_element(count.begin(), count.end(),count.value_comp())->second;
Upvotes: 2