为什么我不能用迭代器访问 const 向量?
我的例子如下。我发现问题出在函数 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
迭代器被定义为返回对所包含对象的引用。如果允许的话,这会破坏向量的常量性。请改用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. Useconst_iterator
instead.