c++ - count_if implementation - C++
问题描述
I am trying myself to create the generic function count_if()
(so I don't have to depend on the inclusion of <algorithm>
by the STL).
This is my code:
template <class InputIterator, class Pred>
int count_if (InputIterator first, InputIterator last, Pred pred) {
int count = 0;
while(first != last ) {
if(pred(*first)) ++count;
++first;
}
return count;
}
I am trying to use this function as the predicate:
bool size_more_than_10(std::string val) {
return val.size() > 10;
}
Problem: my predicate works with std::string
, but when I dereference the iterator I get a char
type, and a compilation error:
error: could not convert ‘__it.__gnu_cxx::__normal_iterator<_Iterator, _Container>::operator*<char*, std::__cxx11::basic_string<char> >()’ from ‘char’ to ‘std::__cxx11::basic_string<char>’
{ return bool(_M_pred(*__it)); }
This is my main
(where I call count_if()
):
int main() {
std::string s;
std::getline(std::cin,s);
std::cout<<"count: "<<count_if(s.begin(),s.end(),size_more_than_10);
return 0;
}
How can I overcome this problem?
解决方案
您错误地使用了这个算法。您的使用会导致字符迭代并且谓词接受字符串。
这是工作示例:
#include <iostream>
#include <iterator>
template <class InputIterator, class Pred>
int count_if (InputIterator first, InputIterator last, Pred pred) {
int count = 0;
while(first != last ) {
if(pred(*first)) ++count;
++first;
}
return count;
}
bool size_more_than_10(std::string val) {
return val.size() > 10;
}
int main()
{
std::cout << count_if(std::istream_iterator<std::string>(std::cin), {}, size_more_than_10) << '\n';
return 0;
}
推荐阅读
- security - 为什么 Mozilla observatory 不能再检测到我网站上的 http 安全标头了?
- beautifulsoup - 如何搜索 Beautiful Soup 树以获取文本匹配的标签路径?
- android - Gradle 7,Android Build-Configuration 文档是否已过时?
- flutter - 如何为 csv 创建工作表
- python - 如何在 discord.py 和 youtube-dl 的播放功能中使用设置队列系统?
- reactjs - Spring Boot 上下文路径不适用于 React 浏览器路由器
- php - php 防止 sscanf() 假设 '-' 作为字符串
- typescript - Typescript 可以推断具体实例中的映射类型,但不能推断泛型类型
- python - Python:带有 MATLAB 函数的 .p 文件
- python - Python数据帧转置时间序列(行到列)