c++ - 如何使用 C++ STL 删除集合中从开始到迭代器之前的一个元素的元素?

标签 c++ algorithm stl set lower-bound

我有一个 setint 作为

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/

相关文章:

c++ - 如何使用for循环计算小数点?

c++ - std::rethrow_exception 因嵌套线程而失败

performance - 从成对列表中提取包的有效算法是什么?

c++ - ReadFile std::unique_ptr 对比 std::vector 对比 std::string

Java 在 C++ 中的 "public static final Object"

c++ - GLSL 错误 : failed to preprocess the source. 我该如何解决这个问题?

algorithm - 连接二维空间中的任意两点

algorithm - 按顺序查找数组中最大的 10% 的数字

c++ - pretty-print 不适用于 C++ STL 列表

c++ - std::map 或 std::list 的 mem_set