具有一段代码来扫描大字符串(html),然后解析出其中的所有单词。如果所有实例都不存在,则将其推入向量或对(单词和计数),否则将计数增加(对的第二个元素)。
vector < pair <string,int> > vect;
vector < pair <string,int> >::iterator it;
...
it = find_if (vect.begin(), vect.end(), currentword);
if (it != vect.end())
it->second++;
else
vect.push_back( make_pair(currentword, 1));
...
获取编译错误:
In file included from C:/TDM-GCC-32/lib/gcc/mingw32/5.1.0/include/c++/bits/stl_algobase.h:71:0, from C:/TDM-GCC-32/lib/gcc/mingw32/5.1.0/include/c++/bits/char_traits.h:39, from C:/TDM-GCC-32/lib/gcc/mingw32/5.1.0/include/c++/ios:40, from C:/TDM-GCC-32/lib/gcc/mingw32/5.1.0/include/c++/ostream:38, from C:/TDM-GCC-32/lib/gcc/mingw32/5.1.0/include/c++/iostream:39, from webCounter.cpp:19: C:/TDM-GCC-32/lib/gcc/mingw32/5.1.0/include/c++/bits/predefined_ops.h: In instantiation of 'bool __gnu_cxx::__ops::_Iter_pred::operator()(_Iterator) [with _Iterator = __gnu_cxx::__normal_iterator, int>*, std::vector, int> > >; _Predicate = std::__cxx11::basic_string]': C:/TDM-GCC-32/lib/gcc/mingw32/5.1.0/include/c++/bits/stl_algo.h:120:14: required from '_RandomAccessIterator std::__find_if(_RandomAccessIterator, _RandomAccessIterator, _Predicate, std::random_access_iterator_tag) [with _RandomAccessIterator = __gnu_cxx::__normal_iterator, int>*, std::vector, int> > >; _Predicate = __gnu_cxx::__ops::_Iter_pred >]' C:/TDM-GCC-32/lib/gcc/mingw32/5.1.0/include/c++/bits/stl_algo.h:161:23: required from '_Iterator std::__find_if(_Iterator, _Iterator, _Predicate) [with _Iterator = __gnu_cxx::__normal_iterator, int>*, std::vector, int> > >; _Predicate = __gnu_cxx::__ops::_Iter_pred >]' C:/TDM-GCC-32/lib/gcc/mingw32/5.1.0/include/c++/bits/stl_algo.h:3815:28: required from '_IIter std::find_if(_IIter, _IIter, _Predicate) [with _IIter = __gnu_cxx::__normal_iterator, int>*, std::vector, int> > >; _Predicate = std::__cxx11::basic_string]' webCounter.cpp:68:58: required from here C:/TDM-GCC-32/lib/gcc/mingw32/5.1.0/include/c++/bits/predefined_ops.h:234:30: error: no match for call to '(std::__cxx11::basic_string) (std::pair, int>&)' { return bool(_M_pred(*__it)); }
答案 0 :(得分:4)
问题是pair <string,int>
与看起来string
之间没有内置比较。您将必须提供一个。例如
it = find_if (vect.begin(),
vect.end(),
[currentword](const pair <string,int>& p){ // this is a lambda expression
return p.first == currentword; // compare strings
});
Documentation for Lambda Expressions
说,
std::map<string, int> freqmap;
如果允许可能是此任务的更好选择。几乎所有代码都简化为
freqmap[currentword]++;