By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,750 Members | 1,199 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,750 IT Pros & Developers. It's quick & easy.

Deleting all but the first element in a set

P: n/a

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

Jul 22 '05 #1
Share this Question
Share on Google+
3 Replies


P: n/a

"Dave" <be***********@yahoo.com> wrote in message
news:10*************@news.supernews.com...

Hello all,

1. Are there any problems with the code below?

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


I don't think so.

john
Jul 22 '05 #2

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

Chris

Dave wrote:
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;
}


Jul 22 '05 #3

P: n/a
Dave wrote:

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
cout << s.size() << endl;
cout << *s.begin() << endl;
}

Jul 22 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.