从大向量中删除字符串列表的有效方法

ags*_*udy 1 c++ stl

我正在使用visual studio 2012(windows),我正在尝试编写一个高效的c ++函数来从一个大的字符串向量中删除一些单词.

我正在使用stl算法.我是一名c ++初学者,所以我不确定这是最好的方法.这就是我所做的:

#include <algorithm>
#include <unordered_set>
using std::vector;

vector<std::string> stripWords(vector<std::string>& input, 
                               std::tr1::unordered_set<std::string>& toRemove){ 
     input.erase(
         remove_if(input.begin(), input.end(), 
                     [&toRemove](std::string x) -> bool {
                         return toRemove.find(x) != toRemove.end();
                     }));
     return input;
}
Run Code Online (Sandbox Code Playgroud)

但这不起作用,它不会遍历所有输入向量.

这是我如何测试我的代码:

vector<std::string>  in_tokens;
in_tokens.push_back("removeme");
in_tokens.push_back("keep");
in_tokens.push_back("removeme1");
in_tokens.push_back("removeme1");
std::tr1::unordered_set<std::string> words;
words.insert("removeme");
words.insert("removeme1");
stripWords(in_tokens,words);
Run Code Online (Sandbox Code Playgroud)

Ker*_* SB 6

你需要两个参数的形式erase.不要超越自己并将其写在不同的行上:

auto it = std::remove_if(input.begin(), input.end(), 
                         [&toRemove](std::string x) -> bool
                         { return toRemove.find(x) != toRemove.end(); });

input.erase(it, input.end());  // erases an entire range
Run Code Online (Sandbox Code Playgroud)