开发者

Why can't I access a const vector with iterator?

开发者 https://www.devze.com 2022-12-29 07:34 出处:网络
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.

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> &bla开发者_如何学运维h)
{
   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;
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消