首页 > 解决方案 > 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?

标签: c++stringalgorithmtemplates

解决方案


您错误地使用了这个算法。您的使用会导致字符迭代并且谓词接受字符串。

这是工作示例

#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;
}

推荐阅读