【问题标题】:Having an error code C2676 with an iterator to a vector of customtype [duplicate]具有指向自定义类型向量的迭代器的错误代码 C2676 [重复]
【发布时间】:2020-04-08 19:13:32
【问题描述】:
vector<element>::iterator it;
it = find(table.begin(), table.end(), temp->c);
if (it != table.end()) {
    table.push_back(*temp);
}

这就是错误发生的地方

struct element {
    char c;
    int freq;
    int first_index;
    struct element* next;
};

vector<element> table;

这是元素结构体和向量的声明。

我需要检查元素是否在向量中,如果不推回。为什么它不起作用?我该如何解决?

这是错误代码:

错误 C2676 二进制“==”:“元素”未定义可以转换为此运算符或预定义运算符可接受的类型的“元素”

【问题讨论】:

  • 请同时发布编译器错误消息。
  • 我更新了帖子
  • 如果元素不存在,如果要添加到向量中,您不想比较迭代器是否为== end()?
  • 什么是temp?

标签: c++ vector iterator


【解决方案1】:

您需要使用std::find_if(),而不是std::find()。

std::find 不起作用的原因是std::find 要求向量中的类型可以使用== 与您正在搜索的值进行比较。由于您只搜索char 类型,但vector 中的类型是element,因此您无法使用== 将element 与char 进行比较(除非您有一个重载的@ 987654332@ 为element 类定义)。

函数std::find_if 允许您指定您希望如何进行比较,因为它不使用== 进行比较。为了进行比较,您将提供一个谓词函数,该函数返回 true 或 false,具体取决于正在测试的项目是否“相等”。

例如,假设 temp 是 element *,我们可以使用 lambda 作为比较函数:

#include <algorithm>
//…
void foo()
{
    element* temp;
    //...
    auto it = std::find_if(table.begin(), table.end(), 
                       // comparison is done here   
                       [&](const element& e) {return e.c == temp->c;});

    if (it == table.end()) 
    {
       // element did not exist
    }
}

【讨论】:

    【解决方案2】:

    std::find() 将输入值与集合中的每个项目进行比较。您正在传递一个 char,但您没有定义可以将整个 element 与单个 char 进行比较的 operator==。这就是错误消息所抱怨的内容。

    由于要比较element 结构的特定字段,因此需要使用std::find_if() 而不是std::find()。

    此外,如果未找到请求的项目,std::find(_if)() 将返回 end 迭代器。如果在向量中未找到新项,您想push_back() 一个新项,您需要使用operator== 将返回的迭代器与end 迭代器进行比较,而不是operator!=。

    试试这个:

    vector<element>::iterator it;
    it = find_if(table.begin(), table.end(),
        [temp](const element &elem){ return elem.c == temp->c; }
    );
    if (it == table.end()) {
        table.push_back(*temp);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-14
      • 2012-12-03
      • 1970-01-01
      • 2012-08-18
      • 1970-01-01
      • 1970-01-01
      • 2012-06-18
      相关资源
      最近更新 更多