【问题标题】:What is returned if list::remove() is used for an element that doesn't exist?如果 list::remove() 用于不存在的元素,会返回什么?
【发布时间】:2023-04-05 05:13:01
【问题描述】:

假设我有一个清单:

list<int> A { 1, 2, 3, 4};

我这样做:

A.remove(5);

这会返回什么?当我在 Visual Studio 中为此创建一个简单的程序时,它运行时不会出现任何错误,所以我假设这是一个法律声明。

但是,如果我想跟踪元素是否被移除,并打印出它已被移除或元素不存在,该怎么办?

例如,有没有这样的:

if (A.remove(5) == true) {
    cout << "Element has been removed" << endl;
} else {
    cout << "Element does not exist" << endl;
}

在第一次调用remove() 函数之前,无需遍历列表并比较每个元素(如果存在)就可以做到这一点?

【问题讨论】:

    标签: c++ stdlist


    【解决方案1】:

    为列表中不存在的值调用list::remove() 是完全合法的。

    在 C++20 之前,list::remove() 没有返回值,因此要知道是否删除了任何元素的唯一方法是在调用 remove() 后检查列表的新 size(),例如:

    list<int> A { 1, 2, 3, 4};
    size_t old_size = A.size();
    A.remove(5);
    if (A.size() < old_size) {
        cout << "Element has been removed" << endl;
    } else {
        cout << "Element does not exist" << endl;
    }
    

    但是,在 C++20 以后,list::remove() 返回删除的元素数量,例如:

    list<int> A { 1, 2, 3, 4};
    if (A.remove(5) > 0) {
        cout << "Element has been removed" << endl;
    } else {
        cout << "Element does not exist" << endl;
    }
    

    无论哪种方式,请注意list::remove() 会删除与指定值匹配的每个元素,因此它必须遍历整个列表以查找所有潜在匹配项。如果您只想删除第一个匹配项,请改用std::find()list::erase(),例如:

    list<int> A { 1, 2, 3, 4};
    auto iter = find(A.begin(), A.end(), 5);
    if (iter != A.end()) {
        A.erase(iter);
        cout << "Element has been removed" << endl;
    } else {
        cout << "Element does not exist" << endl;
    }
    

    【讨论】:

    猜你喜欢
    • 2016-07-24
    • 2013-02-27
    • 2016-07-13
    • 1970-01-01
    • 2012-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多