Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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< 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.

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

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

like image 374
linello Avatar asked Apr 27 '12 13:04

linello


People also ask

How do you get a specific element in a set in C++?

To access a particular index, you can use this : int first = *next(myset. begin(),0); int third = *next(myset. begin(),2);

How do you find the top element of a set?

rend() methods Approach: Elements in a set are stored in sorted order. So the minimum element of the set will reside in the first element and the maximum element in the last element. Therefore, this first and last element can be fetched with the help of set. rend() and set.

How do you access a particular element in a set?

Now, to access an element at nth index we need to create an iterator pointing to starting position and keep on increment the iterator till nth element is reached i.e. std::cout<<"3rd Element in set = "<<*setIt<<std::endl; std::set<std::string>::iterator setIt = setOfStr.


1 Answers

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

like image 169
Binghe Zhai Avatar answered Oct 05 '22 08:10

Binghe Zhai