Deleting all but the first element in a set

D

Dave

Hello all,

1. Are there any problems with the code below?

2. Is there a better way to accomplish what this code does?

Thanks,
Dave

#include <iostream>
#include <set>

using namespace std;

int main()
{
set<int> s;

for (int i = 0; i != 100; ++i)
s.insert(i);

// Erase all elements but the first.
s.erase(++s.begin(), s.end());

cout << s.size() << endl;
cout << *s.begin() << endl;
}
 
F

Fiber Optic

I would just create a new empty set, and copy the first element from the
old one into the new one.

Chris
 
D

Denis Remezov

Dave said:
Hello all,

1. Are there any problems with the code below?

2. Is there a better way to accomplish what this code does?

Thanks,
Dave

#include <iostream>
#include <set>

using namespace std;

int main()
{
set<int> s;

for (int i = 0; i != 100; ++i)
s.insert(i);

// Erase all elements but the first.
s.erase(++s.begin(), s.end());

I cannot think of a situation in which the above would not work,
but I would avoid writing ++s.begin(), even if it were for the
sake of uniformity.

If s were a vector, ++s.begin() might or might not compile, depending
on the definition of the iterator. If the iterator were defined as a
pointer then ++s.begin() would not compile, for the reason that
non-reference return types are not lvalues.

Iterators used by class set are user-defined types (not because they
are required to be such, but because it is impossible to implement them
as pointers and satisfy all set requirements). The result of begin()
is still a non-lvalue, but you can use it with an operator function.

Denis
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,011
Latest member
AjaUqq1950

Latest Threads

Top