C2676 实现结构列表时出现编译错误

C2676 Compiling Error while implementing a list of structs

我正在尝试检查结构列表中是否已经存在具有相同值的元素,所以如果没有,我会向列表推回一个新的 struct.Consider 它就像一个带有帐户的系统,如果有已经是一个帐户我不想再将其添加到列表中。

这是我的主要代码:

accounts test;
test.bal = 0;
test.id = 0;
std::list <accounts> accs;
std::list<accounts>::iterator check;

这是我在 main 之外的代码:

#include <list>
#include <iterator>
#include <algorithm>
struct accounts {
    long id;
    int bal;

};

这是我在 for 循环中的代码:

 check = find(accs.begin(), accs.end(), test.id);
        if (check == accs.end()) {
            accs.push_back(test);
        }

当我 运行 代码时出现编译错误 :

Error C2676 binary '==': 'accounts' does not define this operator or a conversion to a type acceptable to the predefined operator bankacc C:\Program Files (x86)\Microsoft Visual Studio19\Community\VC\Tools\MSVC.28.29333\include\xutility 5440

我看过其他帖子,我想我需要做一个

if(check == accs.id.end())

或类似的东西但它不起作用,显示错误:

Error (active) E0135 class "std::list<accounts, std::allocator>" has no member "id"

有什么想法吗? :)

只需重载运算符“==”即可。在参数中Fetch the desired Type 你想要的值。

原因很简单。当你使用 std::find 时,引擎盖下发生的事情是这样的,

for(iterator i = begin; i != end; i++)
    if(*i == check) return i;

看看这个,你可以看到当我们传入你的列表时,迭代器类型是 std::list<accounts>::iterator 但你检查的是 accounts::id。没有办法做到这一点。

那么有哪些选择呢?你有 3 个,

  1. accounts 结构创建一个 == 运算符。
  2. 传入test即可测试
  3. 传入一个函数来进行比较。

第一个很简单,可以复制粘贴,

struct accounts {
    long id;
    int bal;
    
    bool operator==(const long& otherID) const { return id == otherID; }
};

现在当 std::find 调用 == 运算符时,它知道要做什么。

第三个很简单,使用lambda。

check = find(accs.begin(), accs.end(), [&test](const accounts& other) {
      return other.id == test.id; });
if (check == accs.end()) {
    accs.push_back(test);
}

std::find 将与容器中要查找的类型相同类型的对象作为最后一个参数。在你的情况下,你应该使用 std::find_if 代替:

check = find_if(accs.begin(), accs.end(),
    [&test](const auto& ac) {
      return ac.id == test.id;
    });