[英]“No match operator==” error when using std::equal and namespace
[英]Why the error no match for 'operator==', when using `std::find`?
我正在使用std::find
檢查字符串不在std::vector<std::vector<string>>
錯誤:
no match for 'operator==' (operand types are 'std::vector<std::__cxx11::basic_string<char> >' and 'const char [6]')
不是類型不匹配嗎?
vector< vector< string>>data;
if(find(data.begin(), data.end(), "START") == data.end()){
printf("Missing \"START\"\n");
return true;`
是和否。 錯誤被觸發,因為你有一個“字符串向量的向量”,即有一維太多了。 使用std::vector<std::string>
定義data
,它會起作用。
當您使用std::find()
,它通常實現為宏或模板化函數,它執行實際工作,而不是庫中某處的預編譯運行時函數。 這允許編譯器根據參數的實際類型進行全面優化。
它實際上做什么 - 因為你的容器是一個類 - 試圖找到一個特殊的成員函數std::vector<std::vector<std::string>>::operator==(const char*)
。 它不是直接以這種方式實現的,通常是一個模板,但這在這里並不重要。 重要的事實是它找不到任何帶有參數的operator==()
版本,該參數以某種方式能夠直接或通過轉換接受傳遞的字符串。 原因是您的向量包含向量,因此唯一有效的參數是另一個字符串向量。
錯誤消息的原因已在另一個答案中得到很好的解釋。 我想為這個問題提供一個解決方案。
當你正在努力尋找,如果有任何的std::string
矢量火柴的矢量元素"START"
,你可以使用標准算法的std :: any_of結合一元謂詞返回std::find(vec.cbegin(), vec.cend(), str) != vec.cend()
; 其中vec
是向量向量的每一行。 在此處查看演示
#include <algorithm>
#include <string>
#include <iostream>
#include <vector>
bool isFound(const std::vector<std::vector<std::string>>& data, const std::string &str)
{
const auto found_in_vector = [&str](const std::vector<std::string> & vec)-> bool {
return std::find(vec.cbegin(), vec.cend(), str) != vec.cend(); // if found
};
if (std::any_of(data.cbegin(), data.cend(), found_in_vector))
{
std::cout << "Found\n";
return true;
}
std::cout << "Missing \""<< str << " \"\n";
return false;
}
int main()
{
std::vector<std::vector<std::string>> data;
std::vector<std::string> test{ "START","test" };
data.emplace_back(test);
std::cout << std::boolalpha << isFound(data, std::string{ "START" } );
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.