On Saturday, 22 August 2015 17:20:54 UTC+3,
emak...@gmail.com wrote:
> Objective is to illustrate the usage of iterators in ranged for loop. I have the following piece of code:
>
> #include <iostream>
> class str{
> char *s;
> int c;
> public:
> str(char *x): s {x} {c = 0; while(*x++)c++;}
> struct iterator{
> iterator(char* x) : c {x} {};
> inline iterator& operator ++() {++c; return *this;}
> inline bool operator == (iterator x) {return x.c == this->c;}
> inline bool operator != (iterator x) {return x.c != this->c;}
> inline char operator *() {return *c;}
> char* c;
> };
>
>
> iterator begin(){return iterator(s);}
> iterator end(){return iterator(s+c);}
> };
> int main(){
> str x {(char *)"hello world"};
>
> for(str::iterator c : x) //this gives error*. See below
> std::cout << *c;
The error diagnostic states quite clearly that you attempt to use
'str::iterator' where 'char' is available but it can't convert
'char' to 'str::iterator'. Most likely you wanted that:
for ( char c : x )
std::cout << c;
Read the description of features more carefully and also look at the
examples in book. When compiler complains about what you do but you
think that you did all correctly then it indicates that you misunderstood
how a feature works.