c++ - 为什么我不能使用迭代器访问 const vector ?

标签 c++ stl vector constants

我的例子如下。我发现问题出在函数 void 测试参数中的“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;
}

最佳答案

iterator 被定义为返回对包含对象的引用。如果允许的话,这会破坏 vector 的常量性。请改用 const_iterator

关于c++ - 为什么我不能使用迭代器访问 const vector ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2791870/

相关文章:

c++ - 合并 a 和 b 的 vector

c++ - 在linux中用gcc命令编译C代码时如何包含lib

c++ - 分段故障多项式

c++ - 是否有一种惯用的方法来返回一个可选择拥有其值的指针

c++ - 使用比较器 (C++) 时按降序对 vector 数组进行排序

c++ - 使用迭代器访问元素

C++ 运算符重载 >>

c++ - 对运营商的澄清

c++ - 使用对 vector 的 vector ?

c++ - 如何使用预定义计数在 C++ 中初始化 vector<int> 数组?