使用迭代器打印一个集合的每个成员 [英] Using an iterator to print out every member of a set

查看:155
本文介绍了使用迭代器打印一个集合的每个成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用迭代器打印出一个集合的每个成员。就我可以从其他stackoverflow答案,我有正确的格式。当我运行这个代码,它正确地输出myset的大小是3,但它只输出一次。如果我用* iter取消注释行,Visual Studio会抛出一个运行时异常,说map / set iterator是不可解析的。任何想法为什么?

I'm trying to use an iterator to print out every member of a set. As far as I can tell from other stackoverflow answers, I have the correct formatting. When I run this code, it correctly outputs that the size of myset is 3, but it only outputs ii once. If I uncomment the line with *iter, Visual Studio throws a runtime exception saying that that "map/set iterator is not dereferencable. Any idea why?

int main()
{
set<int> myset;
myset.insert(5);
myset.insert(6);
myset.insert(7);
set<int>::iterator iter;
cout<<myset.size()<<endl;
int ii=0;
for(iter=myset.begin(); iter!=myset.end();++iter);{
    //cout<<(*iter)<<endl;
    ii+=1;
    cout<<ii<<endl;
}
return 0;
}


推荐答案

此行中有一个额外的;

for(iter=myset.begin(); iter!=myset.end();++iter);{

这意味着循环的实体实际上是空的,并且以下行只执行一次。

This means that the loop's body is actually empty, and the following lines are executed once only.

所以改成这样:

for(iter=myset.begin(); iter!=myset.end();++iter) {

这篇关于使用迭代器打印一个集合的每个成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆