为什么我不能用迭代器访问const向量?

4 c++ stl const vector

我的例子如下.我发现问题在函数void test的参数中是"const".我不知道为什么编译器不允许.有人可以告诉我吗?谢谢.

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;
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*som 16

An iterator定义为返回对包含对象的引用.如果允许,这将破坏向量的常量.请const_iterator改用.

  • @yan所有STL容器都有`const_iterator`.而不是声明类似`vector <int> :: iterator`的东西,你声明`vector <int> :: const_iterator`.它将适用于任何符合标准的STL实现.gcc有它.视觉工作室有它.在这一点上,我希望任何甚至模糊不清的编译器都会拥有它.如果不存在,我会感到震惊.如果你遇到问题,你很可能会宣布或使用它. (2认同)