【问题标题】:Why the error no match for 'operator==', when using `std::find`?使用`std::find`时,为什么错误与'operator=='不匹配?
【发布时间】:2019-04-28 05:35:08
【问题描述】:

我正在使用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;`

【问题讨论】:

  • 你有一个向量向量,而不是字符串向量。您的编译器说它无法在向量中找到字符串。

标签: c++ algorithm c++11 stdvector stdstring


【解决方案1】:

错误消息的原因已在其他答案中得到很好的解释。我想为这个问题提供一个解决方案。

正如您试图找到的那样,如果向量的向量中的任何 std::string 元素与 "START" 匹配,则可以使用标准算法 std::any_of 与返回 std::find(vec.cbegin(), vec.cend(), str) != vec.cend()unary predicate 结合使用;其中vec 是向量向量的每一行。 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" } );
}

【讨论】:

  • (data.begin(), data.end(), [](vector&lt;string&gt;vec)-&gt;bool{return find(vec.begin(), vec.end(), "START") == vec.end();}) 我可以这样写labda吗?
  • 但是当我添加std::vector&lt;std::string&gt;test{"START","test"}; data.push_back(test);它仍然是假的
  • @Alvin_Kirin 对不起.. std::find(vec.cbegin(), vec.cend(), str) == vec.cend(); 有错字,应该是std::find(vec.cbegin(), vec.cend(), str) != vec.cend();,将更新答案!
  • 知道了,非常感谢
【解决方案2】:

是和不是。错误被触发,因为你有一个“字符串向量的向量”,即一维太多。改为使用std::vector&lt;std::string&gt; 定义data,它将起作用。

但为什么错误会提到缺少运算符?

当您使用std::find() 时,它通常被实现为一个宏或模板化的函数来执行实际工作,而不是库中某处的预编译运行时函数。这允许编译器根据参数的实际类型进行全面优化。

它实际上做了什么——因为你的容器是一个类——试图找到一个特殊的成员函数std::vector&lt;std::vector&lt;std::string&gt;&gt;::operator==(const char*)。它不是直接以这种方式实现的,通常是模板,但这在这里并不重要。重要的事实是它找不到任何版本的operator==() 的参数能够以某种方式直接或通过转换接受传递的字符串。原因是您的向量包含向量,因此唯一有效的参数是另一个字符串向量。

【讨论】:

  • 所以 data.end() 不返回向量,它只返回向量的成员?
  • @Alvin_Kirin 它返回最后一个元素之后的位置。
猜你喜欢
  • 2021-03-16
  • 2012-08-04
  • 2017-11-25
  • 2019-03-18
  • 2014-07-03
  • 1970-01-01
  • 2020-01-30
  • 2012-03-02
相关资源
最近更新 更多