c++ - 处理 vector 时如何为 find 和 find_if 使用正确的指针

标签 c++ sorting search

我有这样的结构:

struct client
{
    string name;
    double money;
};

我还有 2 个谓词:

bool less_10(const client& a)
{
    return a.money < 10;
}

bool not_a(const client& a)
{
    return a.name.at(0) != 'A';
}

在我的主要功能中,我使用它来过滤存储在 vector client_list 中的结果(每个人的钱 < 10(选择 1)或每个名字不以 A 开头的人(其他))

if (choice_filter == 1)
    {
        vector<client>::iterator it3;
        it3 = find_if(client_list.begin(), client_list.end(), less_10);
        while (it3 != client_list.end())
        {
            **client_list.erase(it3); 
            it3 = find_if(it3 + 1, client_list.end(), less_10);
        }
        client_list.erase(it3);**
    }

    else
    {
        vector<client>::iterator it4;
        it4 = find_if(client_list.begin(), client_list.end(), not_a);

        while (it4 != client_list.end())
        {
            **client_list.erase(it4);
            it4 = find_if(it4 + 1, client_list.end(), not_a);
        }
        client_list.erase(it4);**
}

我注意到如果我先删除,然后 find_if,我会失去最后一个客户。所以我又添加了 1 行来删除,但是程序崩溃了,因为迭代器现在已经到了最后,无法删除。

有什么办法可以解决这个问题吗?我想继续使用带有谓词的 find_if 以及像上面那样的 while 循环,因为它们是必需的。

最佳答案

正如其他人所说,std::remove_if 是最好的解决方案。如果 你这样做是出于教学原因(我怀疑是 这种情况,给定这些特定的谓词):你在 正确的轨道上。唯一的问题是 client_list.erase 使迭代器无效。但是因为它返回一个迭代器 在它删除的元素之后的元素,你可以使用 类似于:

std::vector<Client>::iterator it 
    = std::find_if( client_list.begin(), client_list.end(), predicate );
while ( it != client_list.end() ) {
    it = client_list.erase( it );
    it = std::find_if( it, client_list.end(), predicate );
}

并且您不想在循环后调用删除。迭代器 指定结尾,那里没有要删除的元素。

关于c++ - 处理 vector 时如何为 find 和 find_if 使用正确的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24523099/

相关文章:

c++ - 期望引入类型(枚举类)的成员函数的缩写参数

ios - 使用未指定的索引。考虑添加 ".indexOn": "phone" at/use_frameworks_beta_2/searchIndex to your security rules for better performance

具有两个以上变量的 Swift Google 搜索

javascript - 根据日期值使用 jQuery 对表格进行排序

python - 什么是最好的 Django 搜索应用程序?

c++ - 为什么在抛出异常指针时我应该使用引用捕获

c++ - Box2d。我可以在静态盒子和动态链条形状之间制作旋转接头吗?

python - 在 Python/C++ 的变化文件中用随机数替换数字

python - 聚合后排序和选择(Pandas)

mysql - SQL逻辑: sort result by product of a column and number of colums of a specific type