我有一个 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;
}
输出与上图相同。
关于c++ - 如何使用 C++ STL 删除集合中从开始到迭代器之前的一个元素的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49820366/