【发布时间】:2020-12-19 07:20:00
【问题描述】:
如何删除向量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);
}
}
}
当我试图编译它时。但是我收到了这个错误:
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,
...
【问题讨论】:
-
因为第二个字符串(字母)是固定的,我以后需要它来构造一个矩阵形式,如果它是一个向量会更容易
-
单个字符(如
'a')与只有一个字符的字符串(如"a")不同。你无法比较它们。 -
稍后我需要将其转换为 2d 矢量,我需要在其中进行一些转置操作,所以我只是认为矢量会很容易操作。顺便说一句,谢谢,我会尝试使用字符串。
-
即使已经回答了,我还是将此问题标记为需要澄清,因为问题的标题和正文描述了两种完全不同的意图。
-
@BalaGanesh,我做了更多的更改,但是问题仍然可以改进;例如,由于问题与 IO 无关,您可以删除
//input部分并只输入std::string plaintext{"abcdefghijklmnopqrst"};,因此您可以告诉您希望修改后的alphabets仅包含{"u","v","w","x","y","z"}。
标签: c++ algorithm stdvector stdstring c++-standard-library