2015-10-21 3 views
1

Я пытаюсь найти элемент в диапазоне, охватываемом std::istream_iterator<std::string>, используя std::find. Код не компилируется, выплевывая ошибку о недостаточности дедукции типа шаблонаstd :: find не работает с istream_iterators

error: no matching function for call to 'find(std::istream_iterator >&, std::istream_iterator >&, std::__cxx11::string&)' auto it = std::find(is, end, token);

note: candidate: template typename __gnu_cxx::__enable_if::__value, std::istreambuf_iterator<_CharT> >::__type std::find(std::istreambuf_iterator<_CharT>, std::istreambuf_iterator<_CharT>, const _CharT2&) find(istreambuf_iterator<_CharT> __first,

note: template argument deduction/substitution failed:

Однако, используя the implementation of std::find from cppreference (прямая реализация) делает код компилируется:

#include <iostream> 
#include <iterator> 
#include <sstream> 

// implementation of std::find from cppreference.com 
template<class InputIt, class T> 
InputIt find(InputIt first, InputIt last, const T& value) 
{ 
    for (; first != last; ++first) { 
     if (*first == value) { 
      return first; 
     } 
    } 
    return last; 
} 

int main() 
{ 
    std::istringstream ss("this is a test"); 
    std::istream_iterator<std::string> is(ss); 
    std::istream_iterator<std::string> end; 

    std::string token = "test"; 
    auto it = find(is, end, token); // put std::find here and it won't compile 
    (it != end) ? std::cout << "Found\n" : std::cout << "Not found\n"; 
} 

знает ли один, что случилось с std::find и istream_iterator s? Я, хотя требования к std::find довольно просты: итератор должен быть InputIterator, который istream_iterator есть.

+2

Вы забыли '#include '. работает сейчас: http://coliru.stacked-crooked.com/a/63d8d55d5839d2d1 – NathanOliver

+0

компилирует и отлично работает для меня без обычного поиска. –

ответ

5

no matching function for call to 'find'

Ну, действительно. Вы не приносило std::find в область видимости, введя следующее:

#include <algorithm> 
+1

Это было совершенно глупо с моей стороны ... Спасибо! Я был занят пониманием сообщения об ошибке шаблона ... darn. Голосование, чтобы закрыть вопрос. – vsoftco

+1

Напуганная вещь заключается в том, что 'std :: find', похоже, имеет некоторый перегруженный внешний алгоритм. В противном случае ошибка должна была быть менее сложной, например: 'error: 'find' не является членом 'std'' – vsoftco

+0

@vsoftco: Да, это объявление вперед/дружбы специализации в [' '] (https: //gcc.gnu.org/onlinedocs/libstdc++/libstdc++-api-4.5/a01048_source.html) –