I have a problem with using iterator on the following code? Does anyone know how to fix it?
using StringVec = std::vector<std::string>;
using StringIntMap = std::unordered_map<std::string, int>;
StringIntMap makeWordCounts(const StringVec& words) {
StringIntMap wordcount_map;
std::vector<std::string>::const_iterator iter = words.begin();
while(iter != words.end()) { //error message appears here
if(wordcount_map.count(iter)) {
wordcount_map[iter] = 1;
}else{
int value = wordcount_map.at(iter);
wordcount_map[iter] = value+1;
}
}
return wordcount_map;
}
error message: no viable conversion from
'std::vector<std::string>::const_iterator' (aka '__wrap_iter<const
std::__1::basic_string<char> *>') to 'const
std::__1::unordered_map<std::__1::basic_string<char>, int,
std::__1::hash<std::__1::basic_string<char> >,
std::__1::equal_to<std::__1::basic_string<char> >,
std::__1::allocator<std::__1::pair<const std::__1::basic_string<char>,
int> > >::key_type' (aka 'const std::__1::basic_string<char>')
if(wordcount_map.count(iter)) {
Thank you for your help.
for (const std::string & word : words)is a better way of looping. Aside2: The body of the loop only needs one expression:wordcount_map[*iter]++;