remove_if()究竟是如何工作的?

我参考了许多资源,但无法理解有关它如何修改容器中元素的部分。我写了一些代码来试图理解,谁能解释一下发生了什么?

#include<bits/stdc++.h>
using namespace std;

bool test(char c)
{
    return (c=='a');
}

int isPalindrome(string A) 
{
    remove_if(A.begin(), A.end(), test);
    cout<<A<<'n';   
 }

int main() 
{
    
    string A="aaaaabbbbb";
    isPalindrome(A); 

    return 0;
}

根据我到目前为止的理解,它应该将所有 a 字符移到 b 的右侧,如果我们尝试打印它,我们应该得到

bbbbbaaaaa

相反,我得到

bbbbbbbbbb

回答

std::remove_if,不是std::move_if。它只是删除从test函数中返回 true 的所有元素。现在,为什么额外的bs?好吧,你不应该看到他们。std::remove_if返回一个标记序列新结尾的迭代器,您应该使用返回值相应地调整容器的大小。因此,假设我们有一个字符串"Hello, World!",我们需要从中删除所有l's。这是一个示例程序,用于显示执行此操作的一种方法:

#include <algorithm>
#include <string>
#include <iostream>

int main()
{
    std::string a = "Hello, World!";
    a.resize(std::distance(
        a.begin(),
        std::remove_if(a.begin(), a.end(), [](char c){return c == 'l';})
    ));
    std::cout << a << 'n';
}

输出:

Heo, Word!

  • The idiomatic way is to use `a.erase(std::remove_if(...), std::end(a))`. Your approach works, but not every container has `resize`. The `erase` approach works for all containers which don't have a fixed size.

以上是remove_if()究竟是如何工作的?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>