Ваш текущий код не может работать, так как вы не удаляете слова из каждой отдельной строки. Ваш erase/remove_if
вызов берет всю строку и пытается сопоставить слово в наборе со всей строкой.
Во-первых, вы должны написать простую функцию, которая, если дано std::string
и карта слов для удаления, возвращает строку с удаленными словами.
Вот небольшая функция, использующая std::istringstream
, которая может сделать это:
#include <unordered_set>
#include <sstream>
#include <string>
#include <iostream>
std::string remove_stop_words(const std::string& src, const std::unordered_set<std::string>& stops)
{
std::string retval;
std::istringstream strm(src);
std::string word;
while (strm >> word)
{
if ( !stops.count(word) )
retval += word + " ";
}
if ( !retval.empty())
retval.pop_back();
return retval;
}
int main()
{
std::string test = "this is a test";
std::unordered_set<std::string> stops = {"is", "test"};
std::cout << "Changed word:\n" << remove_stop_words(test, stops) << "\n";
}
Выход:
Changed word:
this a
Так что, как только у вас все будет работать правильно, версия std::vector
- это не что иное, как цикл по каждому элементу в векторе и вызов функции remove_stop_words
:
int main()
{
std::vector<std::string> test = {"this is a test", "another a test"};
std::unordered_set<std::string> stops = {"is", "test"};
for (size_t i = 0; i < test.size(); ++i)
test[i] = remove_stop_words(test[i], stops);
std::cout << "Changed words:\n";
for ( auto& s : test )
std::cout << s << "\n";
}
Выход:
Changed words:
this a
another a
Обратите внимание, что вы можете использовать функцию std::transform
для удаления скрученной вручную петли в приведенном выше примере:
#include <algorithm>
//...
int main()
{
std::vector<std::string> test = {"this is a test", "another a test"};
std::unordered_set<std::string> stops = {"is", "test"};
// Use std::transform
std::transform(test.begin(), test.end(), test.begin(),
[&](const std::string& s){return remove_stop_words(s, stops);});
std::cout << "Changed words:\n";
for ( auto& s : test )
std::cout << s << "\n";
}