C++ 使用迭代器打印出集合的每个成员

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10742491/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 14:24:13  来源:igfitidea点击:

Using an iterator to print out every member of a set

c++iteratorset

提问by user1415670

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?

我正在尝试使用迭代器打印出集合的每个成员。据我从其他stackoverflow答案中可以看出,我有正确的格式。当我运行此代码时,它正确输出 myset 的大小为 3,但它只输出 ii 一次。如果我用 *iter 取消注释该行,Visual Studio 会抛出一个运行时异常,指出“map/set iterator is not dereferencable。知道为什么吗?

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

回答by Smi

You have an extra ;in this line:

;在这一行有一个额外的:

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.

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

So change that line to this:

因此,将该行更改为:

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