c++ 中的 set 如何删除元素

在 C++ 中,可以使用 std::set 容器中的 erase() 成员函数来删除指定元素#include #include int main() {std::set my_set = {1, 2, 3, 4, 5};// 查找要删除的元素int element_to_remove = 3;auto it = my_set.find(element_t

C++ 中,可以使用 std::set 容器中的 erase() 成员函数来删除指定元素

#include <iostream>
#include <set>

int main() {
    std::set<int> my_set = {1, 2, 3, 4, 5};

    // 查找要删除的元素
    int element_to_remove = 3;
    auto it = my_set.find(element_to_remove);

    if (it != my_set.end()) {
        // 如果找到了元素,则删除它
        my_set.erase(it);
        std::cout << "Element " << element_to_remove << " has been removed from the set." << std::endl;
    } else {
        std::cout << "Element " << element_to_remove << " not found in the set." << std::endl;
    }

    // 输出修改后的集合
    for (const auto& elem : my_set) {
        std::cout << elem << " ";
    }

    return 0;
}

在这个示例中,我们首先创建了一个包含整数的 std::set。然后,我们使用 find() 函数查找要删除的元素。如果找到了该元素,我们使用 erase() 函数将其从集合中删除。最后,我们遍历并输出修改后的集合。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,请发送邮件至 55@qq.com 举报,一经查实,本站将立刻删除。转转请注明出处:https://www.szhjjp.com/n/1201418.html

(0)
派派
上一篇 2024-11-29
下一篇 2024-11-29

发表回复

登录后才能评论