#include<iostream>
#include<list>

using namespace std;
                  
int main()
{
  list<int> dob;

    for(int i=0;i<5;i++)
    {
       dob.push_back(i);
    } 

   for(int i=0,list<int>::iterator itr=dob.begin();i<3;itr++,i++)
      cout<<*itr; 

 return 0;
}

errors--

test.cpp: In function `int main ()':
test.cpp:17: `iterator' specified as declarator-id
test.cpp:17: extraneous `int' ignored
test.cpp:17: `int list<int, allocator<int> >::iterator' is not a static
member of `class list<int, allocator<int> >'
test.cpp:17: parse error before `='
test.cpp:17: `itr' undeclared (first use this function)
test.cpp:17: (Each undeclared identifier is reported only once for each
function it appears in.)

Recommended Answers

All 3 Replies

Try this:

for( list<int>::iterator itr = dob.begin(); itr != dob.end(); itr++ )
{
    cout << *itr;
}

I am not sure about the starting expression of the for loop, but as far as I know. You can declare as many arguments as you want to, as long as they are from the same type.

for( int a = 0, b = 0, c = 0, d = 0; d < 15 ; a++, b++, c++, d++ )
{
 //...
}

I am assuming it doesn't like it, when you are trying to mix it. I tried to find more about the for statement but I had no luck with it. :( I only get the standard examples. This one is the best I've found so far. http://mathbits.com/mathbits/compsci/looping/for.htm

Add #include<iterator>. It may help.

you can't use the comma operator to declare variables of a different types -- they must all be the same type. So I'd code it like this (making the iterator global to the function instead of just the loop):

list<int>::iterator itr = bob.begin();
for(int i=0;i<3 && itr != bob.end();itr++,i++)
      cout<<*itr;
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.