C++ 如何获取 std::set 的第一个元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10351591/
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 13:55:46  来源:igfitidea点击:

How to get the first element of a std::set

c++stliteratorset

提问by linello

I you all,

我你们,

I found a strange bug in my software.

我在我的软件中发现了一个奇怪的错误。

Inside a while loop where I remove elements from a std::set, I want always to take the first element until the container is empty:

在我从 std::set 中删除元素的 while 循环中,我希望始终获取第一个元素,直到容器为空:

std::set< int*> nodes;
// Fill nodes 
for (int i=0; i<10;i++)
   nodes.insert(new int);
//
while (!nodes.empty())
{
int* pivot  = (*nodes.begin());
// do some operation with pivot erasing some elements from nodes
}

I found that implementing the first element this way works with gcc but not with MSVC, it crashes where I try to dereference the (*nodes.begin())iterator.

我发现以这种方式实现第一个元素适用于 gcc 但不适用于 MSVC,它在我尝试取消引用(*nodes.begin())迭代器时崩溃。

Do the two implementation of std::set behave differently?

std::set 的两个实现的行为是否不同?

I would like to have a data structure with no differences of implementation, is it possible?

我想要一个没有实现差异的数据结构,这可能吗?

Probably I must change data structure for this kind of operations

可能我必须为这种操作更改数据结构

采纳答案by Binghe Zhai

your code work well in VS2010, mybe you should update your vcc.

您的代码在 VS2010 中运行良好,您应该更新您的 vcc。

回答by Rob

You can't use an iterator on a set like this as removing an element from the set invalidates the iterator. When the size of the set gets below a certain threshold (based on the initial size when you set up the iterator) it will modify the underlying storage of your data on the heap, which will leave the pointer that is your iterator pointing to crap.

您不能在这样的集合上使用迭代器,因为从集合中删除元素会使迭代器失效。当集合的大小低于某个阈值(基于设置迭代器时的初始大小)时,它将修改堆上数据的底层存储,这将使迭代器的指针指向垃圾。

See under iterator validity: http://www.cplusplus.com/reference/set/set/erase/

查看迭代器有效性:http: //www.cplusplus.com/reference/set/set/erase/

(*nodes.begin()) does what you want, you just can't delete from a set your iterating through

(*nodes.begin()) 做你想做的,你只是不能从你迭代的集合中删除