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

发布于 2024-08-31 22:16:38 字数 395 浏览 3 评论 0原文

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

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;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

想你的星星会说话 2024-09-07 22:16:38

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文