Why can't I access the vector constants using an iterator?

My example is as follows. I found out that the problem is "const" in the parameter of the void function. I don't know why the compiler doesn't allow. Can anyone 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;
}

      

+2


a source to share


1 answer


An is iterator

defined to return a reference to the contained object. This would destroy the consistency of the vector if it were allowed. Use instead const_iterator

.



+16


a source







All Articles