STL 迭代器返回 const 对象吗?
我们已经很长时间没有使用 STL 了,所以任何帮助将不胜感激。不知道我们在这里做错了什么...... 鉴于此,为什么此代码会抛出错误:
“您无法分配给 const 变量”
struct person
{
int age;
bool verified;
string name
bool operator< (person const &p)
{
return (age < p.age);
}
};
multiset<person> msPerson;
multiset<person>::iterator pIt;
// add some persons
while (adding people)
{
Person p;
p.name=getNextName();
p.age=getNextAge();
msPerson.insert(p);
}
pIt = msPerson.begin();
// try to verify
pIt->verified = true; <---- **error here....**
It's been a long time since we used STL so anyhelp would be appreciated. Not sure what we're doing wrong here...
Given this, why does this code throw an error:
"you cannot assign to a variable that is const"
struct person
{
int age;
bool verified;
string name
bool operator< (person const &p)
{
return (age < p.age);
}
};
multiset<person> msPerson;
multiset<person>::iterator pIt;
// add some persons
while (adding people)
{
Person p;
p.name=getNextName();
p.age=getNextAge();
msPerson.insert(p);
}
pIt = msPerson.begin();
// try to verify
pIt->verified = true; <---- **error here....**
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果容器是有序的,它们会返回一个 const 迭代器。这个想法是,如果您更改内容,容器不知道并且无法保证顺序。矢量没有,但地图有。
如果您确定您的更新不会影响排序顺序,您可以放弃常量。如果您这样做,请一如既往地谨慎行事。
They return a const iterator if the container is ordered. The idea is that if you change the content the container doesn't know and it cannot guarantee order. Vector does not, but map does.
If you're sure your update does not affect the sort order you can cast away the const-ness. As always proceed with caution if you do that.
set 返回只读迭代器。 stl 中的其他容器则没有(例如向量)。
sets return read-only iterators. Other containers in stl do not (e.g. vector).
你应该使用
->没有为 STL 迭代器定义运算符。
You should use
-> operator isn't defined for STL iterators.