如何使用 C++ stl 删除集合中从开始到迭代器之前的一个元素的元素?
How to delete elements in a set from begining till one element before iterator using c++ stl?
我有一个 set
的 int
作为
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);
我要删除 2 到 5。
我目前正在尝试这样做 ds.erase(ds.begin(), --it);
但是代码冻结并且没有进一步的进展。此外,如果在迭代器位置之前没有元素,我不想删除任何内容。
如何使用c++ STL实现?
给你。
#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;
}
程序输出为
6 7 8
或者
#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;
}
输出与上图相同。
首先 it
指向 6
,--it
将其更改为 5
。在 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.
因此您可以简单地使用 it
而不是 --it
。
ds.erase(ds.begin(),it);
我有一个 set
的 int
作为
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);
我要删除 2 到 5。
我目前正在尝试这样做 ds.erase(ds.begin(), --it);
但是代码冻结并且没有进一步的进展。此外,如果在迭代器位置之前没有元素,我不想删除任何内容。
如何使用c++ STL实现?
给你。
#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;
}
程序输出为
6 7 8
或者
#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;
}
输出与上图相同。
首先 it
指向 6
,--it
将其更改为 5
。在 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.
因此您可以简单地使用 it
而不是 --it
。
ds.erase(ds.begin(),it);