2013-11-06 4 views
0
#include <iostream> 
#include <algorithm> 
using namespace std; 

template<class Iterator, class T> 
Iterator find_my(Iterator first, Iterator last, const T& v) 
{ 
while(first!=last && *first!=v) 
    ++first; 
return first; 
} 

struct int_node 
{ 
int val; 
int_node* next; 
}; 

template<class Node> 
struct node_wrap 
{ 
Node* ptr; 
node_wrap(Node* p = NULL) : ptr(p) { } 

Node& operator*() const { return *ptr; } 
Node* operator->() const { return ptr; } 

node_wrap& operator++() { ptr = ptr->next; return *this; } 
node_wrap& operator++(int) { node_wrap tmp = *this; ++this; return tmp; } 

bool operator==(const node_wrap& i) const { return ptr == i.ptr; } 
bool operator!=(const node_wrap& i) const { return ptr != i.ptr; } 
}; 

bool operator==(const int_node& node, int n) 
{ 
return node.val == n; 
} 

bool operator!=(const int_node& node, int n) 
{ 
return node.val != n; 
} 

int main() 
{ 
int_node* nod[10]; 
for(int i = 0; i<10; i++) 
{ 
    int b,j; 
    j=i; 
    cout << "\nEnter number: "; 
    cin >> b; 
    nod[i] = new int_node; 
    nod[i]->val = b; 
    if(i==0) 
     nod[i]->next = NULL; 
    else 
     nod[i]->next = nod[--j]; 
} 

int a; 
cout << "\nWhich number do you find: "; 
cin >> a; 
node_wrap<int_node> first(nod[9]); 


node_wrap<int_node> search = find_my(first,node_wrap<int_node>(), a); 


if(search != node_wrap<int_node>()) 
    cout << "\nAll is good: " << a; 
cout << "\nIf not good, then Bad"; 
cout << endl; 
system("pause"); 
return 0; 
} 

Я делаю свой Iterator, который называется struct struct_wrap для типа int_node. Проблема в том, что стандартная функция find from не хочет работать с этим Iterator (node_wrap). Но с моей собственной функцией find_my() он работает хорошо. Что я сделал не так? Спасибо.std :: find не хотят работать с собственной оболочкой класса

Компилятор выдает много ошибок. Например:

error C2868: 'std::iterator_traits<_Iter>::difference_type' : 
illegal syntax for using-  declaration; 
expected qualified-name 
1>   with 
1>   [ 
1>    _Iter=node_wrap<int_node> 
1>   ] 
1>c:\program files (x86)\microsoft visual studio 11.0\vc\include\xutility(368): 
error C2039: 'pointer' : is not a member of 'node_wrap<Node>' 
1>   with 
1>   [ 
1>    Node=int_node 
1>   ] 
+2

«Не хочу работать с». Что это значит? Ошибки компилятора, ошибка времени выполнения, неожиданный результат? Просьба уточнить и отложить свой код должным образом. – jrok

ответ

2

std::find нуждается в дополнительной информации о вашем типе для правильной работы. В частности, std::iterator_traits должен работать с вашим итератором:

template<class Node> 
struct node_wrap 
{ 
    typedef void difference_type; // you should use another difference type 
    typedef Node value_type; 
    typedef Node* pointer; 
    typedef Node& reference; 
    typedef std::forward_iterator_tag iterator_category; 

    // ... 
}; 
Смежные вопросы