Reputation: 3151
I have a set
of int
s as
set<int> ds;
ds.insert(2);
ds.insert(3);
ds.insert(4);
ds.insert(5);
ds.insert(6);
ds.insert(7);
ds.insert(8);
set<int>::iterator it = lower_bound(ds.begin(), ds.end(), 6);
I want to delete 2 till 5.
I am currently trying to do like ds.erase(ds.begin(), --it);
But the code freezes and does not progress further. Also, I would not want to erase anything if there are no elements prior to the iterator location.
How to achieve it using c++ STL?
Upvotes: 0
Views: 129
Reputation: 1691
First it
is pointing to 6
and --it
changes it 5
. In std::map.erase(first, last)
Iterators specifying a range within the map container to be removed: [first,last). i.e., the range includes all the elements between first and last, including the element pointed by first but not the one pointed by last.Member types iterator and const_iterator are bidirectional iterator types that point to elements.
So you can simply use it
instead --it
.
ds.erase(ds.begin(),it);
Upvotes: 1
Reputation: 310950
Here you are.
#include <iostream>
#include <set>
int main()
{
std::set<int> ds = { 2, 3, 4, 5, 6, 7, 8 };
ds.erase( ds.begin(), ds.lower_bound( 6 ) );
for ( int x : ds ) std::cout << x << ' ';
std::cout << std::endl;
return 0;
}
The program output is
6 7 8
Or
#include <iostream>
#include <set>
#include <algorithm>
int main()
{
std::set<int> ds = { 2, 3, 4, 5, 6, 7, 8 };
ds.erase( ds.begin(), std::lower_bound( ds.begin(), ds.end(), 6 ) );
for ( int x : ds ) std::cout << x << ' ';
std::cout << std::endl;
return 0;
}
The output is the same as shown above.
Upvotes: 4