我目前正在撰寫一個接收 astring作為輸入的代碼,檢查它是否僅由car_acc陣列中的字符組成,如果不是,則使用 do-while 回圈再次請求輸入。
這是代碼:
char car_acc [11] = {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0', ':'};
deque <bool> contr_car;
do
{
cout << "Inserire il tempo di attesa (ore:minuti:secondi) -> ";
cin >> tempo; fflush (stdin);
lung = (int) tempo.length ()-1;
for (; i != lung; i =1)
{
contr_car [i] = false;
}
for (i = 0; i != 11; i =1)
{
if (car_acc [i] == tempo [j])
{
contr_car [j] = true;
}
}
}
while (all_of (contr_car [0], contr_car [lung], true) == false);
我正在使用contr_car雙端佇列來存盤其中的每個字符string是否等于存盤在car_acc陣列中的字符之一。
我收到此錯誤,在algorithm頭檔案中鏈接:
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c /v1/algorithm:926:21: Indirection requires pointer operand ('int' invalid)
錯誤發生在定義all_of函式的檔案部分:
template <class _InputIterator, class _Predicate>
inline _LIBCPP_INLINE_VISIBILITY
bool
all_of(_InputIterator __first, _InputIterator __last, _Predicate __pred)
{
for (; __first != __last; __first)
if (!__pred(*__first)) // error's here
return false;
return true;
}
我也在同一行收到此訊息while:
In instantiation of function template specialization 'std::__1::all_of<bool, bool>' requested here
使用該find ()函式代替all_of ()并不能修復錯誤。
我正在使用雙端佇列,因為我必須在回圈之外宣告它,在回圈內部我得到大小,所以陣列不是一個選項,我真的不知道如何使用vector <bool>,因為它作為一個位集作業. 我確實包括了algorithm和deque標題。我嘗試使用 avector <int>但它仍然無法正常作業,它只會更改我在 a 所在的行上收到的訊息while:
In instantiation of function template specialization 'std::__1::all_of<int, int>' requested here
老實說,我不知道如何解決它,因為我剛剛開始使用 C 和一般的編碼,所以如果你能以一種易于理解的方式表達你的答案,我會非常感激。
uj5u.com熱心網友回復:
該演算法std::all_of旨在對迭代序列中的每個元素呼叫一元謂詞,從每個元素中獲取“真”或“假”,并以包含“真”(所有報告為真)或“假”(至少一個事情報告錯誤)。為此,您需要提供三件事:
- 開始迭代器
- 結束迭代器
- 回傳布林值的可呼叫一元謂詞。
您的代碼完全不提供這些,因此難怪它不會編譯。下面顯示了如何使用std::all_of的示例。它不是千篇一律的,所以請不要有其他想法。
#include <iostream>
#include <algorithm>
#include <unordered_set>
#include <string>
int main()
{
const std::unordered_set<char> car_acc = {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0', ':'};
std::string tempo;
do
{
std::cout << "Inserire il tempo di attesa (ore:minuti:secondi) -> ";
std::cout.flush();
if (!(std::cin >> tempo))
{
// TODO: handle failure on stdin
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
} while ( !std::all_of(tempo.begin(), tempo.end(),
[&car_acc](char c){return car_acc.find(c) != car_acc.end();}) );
std::cout << "You entered: " << tempo << '\n';
}
這只是創建一個包含您認為是“允許”字符的無序集,然后使用該集作為這里一元謂詞的基礎,一個簡單的 lambda:
[&car_acc](char c){return car_acc.find(c) != car_acc.end();}
然后std::all_of使用字串開始和結束迭代器將其饋入。如果字串中的任何字符未能在集合中找到匹配項,則該匹配檢查的結果將為 false,因此也應為std::all_of.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/459928.html
