我正在從 codewars.com 做一個練習作業,以創建一個程式,該程式將接收巨魔的評論并將其轉換為沒有元音的陳述句。
我的想法是獲取注釋,回傳所有不是元音的字符,并使用迭代器將其放入新的字串陣列中。
int main()
{
string troll;
string disemvoweled;
getline(cin,troll);
int length= (int) troll.length();
string::iterator it;
for (it = troll.begin();it!=troll.end();it ) {
if (*it!='a' || *it!='e' || *it!='i' || *it!='o' || *it!='u' || *it!='A' || *it!='E' ||*it!='I' || *it!='O' || *it!='U'){
disemvoweled.append(*it);
}
}
cout << disemvoweled;
return 0;
}
我收到一個錯誤:
no matching function for call to std::__cxx11::basic_string<char>::append(char&)'
我的第一個問題是為什么 append() 不起作用?
我的第二個問題是,在沒有提供任何解決方案的情況下,C 的哪個概念可以幫助我改進這段代碼?我在想也許使用某種容器并彈出一個元音?
uj5u.com熱心網友回復:
為什么 append() 不起作用?
append可以在此處找到的多載,正如您所看到的,它們期望不同型別的引數(例如const std::string&,const char*)當您提供char型別引數時。
您可以使用以下方法解決此問題 =:
disemvoweled = (*it);
C 的哪個概念可以幫助我改進這段代碼?
您可以使用以下方法改進代碼std::set:
getline(cin,troll);
std::set<char> vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E','I','O','U'};
for (auto it = troll.begin();it!=troll.end();it ) {
if (vowels.find(*it) == vowels.end())
{
disemvoweled = (*it); //can also use disemvoweled.append(1, *it);
}
}
cout << disemvoweled;
uj5u.com熱心網友回復:
您可以使用range-v3:
#include <string>
#include <iostream>
#include <range/v3/all.hpp>
constexpr bool is_not_vowel(char const ch) noexcept {
switch (ch) {
case 'a': case 'e': case 'i': case 'o': case 'u':
case 'A': case 'E': case 'I': case 'O': case 'U':
return false;
default:
return true;
}
}
int main() {
std::string str = "hello world";
std::string no_vowels;
ranges::copy(
str | ranges::views::filter(is_not_vowel),
std::back_inserter(no_vowels)
);
std::cout << no_vowels << '\n';
}
在線查看
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/356542.html
