文字列に特定の単語が含まれている場合、文字列のベクトルからいくつかの要素を削除する必要があります。
remove_if
の単項述語を書く方法
?
コードサンプルは次のとおりです。
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
bool remove_if_found(string word)
{
// ???
}
int main()
{
vector<string> data {
{ "the guitar has six strings" },
{ "the violin has four strings" },
{ "the the violin is more difficult to learn" },
{ "saxophones are a family of instruments" },
{ "the drum is a set of percussions" },
{ "the trumpet is a brass" }
};
cout << data.size() << endl; // output: 6
remove_if(data.begin(), data.end(), remove_if_found("violin")); // error
cout << data.size() << endl; // output should be: 4
return 0;
}
問題は、式
remove_if_found("violin")
bool
を返しますstd::remove_if
に渡すことはできません 。あなたにとって最も簡単な解決策は、
remove_if_found
を変更することです など:これは、検索する文字列だけでなくベクトルへの参照を取り、通常どおり削除を行います。
その後、
main
で あなたはそれをそのように呼ぶだけです:remove_if_function
でerase + removeを使用する理由 は重要。std::remove_if
単に削除したい要素をベクトルの最後に移動し、(再)移動した要素の最初にイテレータを返します。一方、std::vector::erase
2つのイテレータを取ります-std::remove_if
から返されたイテレータ イテレータとvec.end()
そして実際にそれらをベクトルから消去します。