I am using std::find
to check a string isn't in std::vector<std::vector<string>>
Error:
no match for 'operator==' (operand types are 'std::vector<std::__cxx11::basic_string<char> >' and 'const char [6]')
Isn't it the type doesn't match?
vector< vector< string>>data;
if(find(data.begin(), data.end(), "START") == data.end()){
printf("Missing \"START\"\n");
return true;`
Yes and no. The error is triggered, because you've got a "vector of vectors of strings", ie there's one dimension too much. Define data
using std::vector<std::string>
instead and it will work.
When you use std::find()
, it's typically implemented as a macro or templated function, which does the actual work, rather than a precompiled runtime function somewhere in a library. This allows the compiler full optimization based on the actual types of your parameters.
What it actually does - since your container is a class - is trying to find a special member function, std::vector<std::vector<std::string>>::operator==(const char*)
. It's not directly implemented this way, typically a template instead, but that's not important here. The important fact is it won't find any version of operator==()
with an argument that is somehow able to accept the string passed, either directly or through conversion. Reason for this is that your vector contains vectors, so the only valid argument would be another vector of strings.
The reason for the error message has been well explained in the other answer. I would like to provide a solution to the problem.
As you are trying to find, if any of the std::string
element in the vector of vector matches to "START"
, you could use standard algorithmstd::any_of in combination with a unary predicate which returns std::find(vec.cbegin(), vec.cend(), str) != vec.cend()
; where vec
is the each rows of the vector of vectors. See a demo here
#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" } );
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.