This is the mail archive of the libstdc++@gcc.gnu.org mailing list for the libstdc++ project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

Re: Strange error with list iterator


Giuseppe Martino wrote:

> Compiling this sources:
>
> #include <list>
> #include <string>
> #include <iostream>
>
> using namespace std;
>
> int main()
> {
>     list<string> l;
>     l.push_back("ciao");
>     typedef std::list <string>::iterator it;
>     for(it i=l.begin(); i<l.end(); i++)
>         cout<<*i;
> }
>
> i have tried to compile it with gcc-3.0.0 and gcc-3.0.2 but it's the same
> Compiling with the command:
> g++ -ansi -pedantic -Wall -c show.cpp
>
> show.cpp: In function `int main()':
> show.cpp:12: no match for `int main()::it& < std::_List_iterator<std::string,
>    std::string&, std::string*>' operator
> make: *** [show.o] Error 1
> it's seem that l.begin() return a reference. what is the problem?

Basically, the problem with your testcase is that the list container does not
provide random access, i.e., does not provide random access iterators. Therefore
you cannot use the < operator, available for random access iterators. Indeed, a
common advice is that of using the != idiom insteaf of the < idiom, in general,
even when using random access containers.
Anyway, change your for condition to (it i=l.begin(); i != l.end(); i++) and the
code will compile.

Cheers,
Paolo Carlini.






Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]