views:

107

answers:

1

My example is as below. I found out the problem is with "const" in function void test's parameter. I don't know why the compiler does not allow. Could anybody tell me? Thanks.

vector<int> p;

void test(const vector<int> &blah)
{
   vector<int>::iterator it;
   for (it=blah.begin(); it!=blah.end(); it++)
   {
      cout<<*it<<" ";
   }
}

int main()
{
   p.push_back(1);
   p.push_back(2);
   p.push_back(3);
   test(p);

   return 0;
}
+15  A: 

An iterator is defined as returning a reference to the contained object. This would break the const-ness of the vector if it was allowed. Use const_iterator instead.

Mark Ransom
I tried it with qt creator on a linux platform and there is no const_iterator
yan bellavance
@yan All STL containers have `const_iterator`. Instead of declaring something like `vector<int>::iterator`, you declare `vector<int>::const_iterator`. It's going to be there in any standards compliant STL implementation. gcc has it. visual studio has it. At this point, I'd expect any compiler that is even vaguely recent would have it. I'd be stunned if it isn't there. You're likely declaring or using it wrong if you're having problems with it.
Jonathan M Davis
@Jonathan, any standards compliant implementation has the declarations/definitions on STL containers. non-STL compliant containers are free to do as they see fit...
Nathan Ernst
@Nathan True. But then they wouldn't necessarily declare iterator either. In either case, yan said nothing about what container he was using, just the IDE. So, I assumed that he was talking about an STL container. If not, then that's an entirely different ballgame.
Jonathan M Davis
try it, you will see.
yan bellavance