Bal*_*esh 8 c++ algorithm stdstring stdvector c++-standard-library
如何删除向量alphabets中与字符串中的任何字符匹配的元素plaintext?
这是我的尝试:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
int main()
{
//init
std::vector<std::string> alphabets{ "a", "b", "c", "d", "e", "f", "g", "h", "i", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" };
//input
std::string plaintext;
std::cout << "enter plain text: ";
std::cin >> plaintext;
for (std::string::iterator it = plaintext.begin(); it != plaintext.end(); it++)
{
std::vector<std::string>::iterator toErase;
toErase = std::find(alphabets.begin(), alphabets.end(), *it);
if (toErase != alphabets.end())
{
alphabets.erase(toErase);
}
}
}
Run Code Online (Sandbox Code Playgroud)
当我试图编译它时。但我收到了这个错误:
17: note: 'std::__cxx11::basic_string<char>' is not derived from
'const std::istreambuf_iterator<_CharT, _Traits>' { return *__it == _M_value; }
...
203 : 5 : note : candidate : 'template<class _CharT, class _Traits> bool
std::operator==(const std::istreambuf_iterator<_CharT, _Traits>&, const
std::istreambuf_iterator<_CharT, _Traits>&)'
operator==(const istreambuf_iterator<_CharT, _Traits> & __a,
...
Run Code Online (Sandbox Code Playgroud)
的*it类型为charnot std::string。这就是编译器所抱怨的。因此,您需要按如下方式将 a 传递std::string给 the std::find。
auto toErase = std::find(alphabets.begin(), alphabets.end(), std::string{ *it });
// ^^^^^^^^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)
这是一个演示。
另外,请注意以下事项:
std::vector<std::string> alphabets为 a
std::vector<char> alphabets甚至单个,std::string因为您的
alphabetscontains/ 将chars表示为字符串。在std::strings (即alphabets)的情况下, thestd::basic_string::find
更适合使用,而不是std::find首先更通用。std::vector其自身的非成员函数,即
std::erase_if.