реализация count_if - C ++ - PullRequest
       2

реализация count_if - C ++

0 голосов
/ 04 сентября 2018

Я пытаюсь себя создать универсальную функцию count_if() (поэтому я не должен зависеть от включения <algorithm> в STL).

Это мой код:

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

Проблема: мой предикат работает с std::string, но при разыменовании итератора я получаю тип char и ошибку компиляции:

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

Это мой main (где я звоню 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;
}

Как мне преодолеть эту проблему?

1 Ответ

0 голосов
/ 04 сентября 2018

Вы используете этот алгоритм неправильно. Ваше использование вызывает итерацию по символам и предикат принимает строку.

Вот рабочий пример :

#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;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...