C2676:二进制“<":“const _Ty"未定义此运算符或转换为预定义运算符可接受的类型

C2676: binary #39;lt;#39;: #39;const _Ty#39; does not define this operator or a conversion to a type acceptable to the predefined operator(C2676:二进制“lt;:“const _Ty未定义此运算符或转换为预定义运算符可接受的类型)

本文介绍了C2676:二进制“<":“const _Ty"未定义此运算符或转换为预定义运算符可接受的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于下面的代码,我不断收到此错误.

I keep getting this error for the code below.

在阅读this后,我相信我的错误是成为 for 循环中的 it++,我尝试将其替换为 next(it, 1) 但它没有解决我的问题.

Upon reading this, I believed my error to be the it++ in my for loop, which I tried replacing with next(it, 1) but it didn't solve my problem.

我的问题是,迭代器是给我带来问题的那个吗?

My question is, is the iterator the one giving me the issue here?

#include <iostream>
#include <vector>
#include <stack>
#include <set>
using namespace std;

struct Node
{
    char vertex;
    set<char> adjacent;
};


class Graph
{
public:
    Graph() {};
    ~Graph() {};

    void addEdge(char a, char b)
    {
        Node newV;
        set<char> temp;
        set<Node>::iterator n;

        if (inGraph(a) && !inGraph(b)) {
            for (it = nodes.begin(); it != nodes.end(); it++)
            {
                if (it->vertex == a)
                {
                    temp = it->adjacent;
                    temp.insert(b);
                    newV.vertex = b;
                    nodes.insert(newV);
                    n = nodes.find(newV);
                    temp = n->adjacent;
                    temp.insert(a);
                }
            }
        }
    };

    bool inGraph(char a) { return false; };
    bool existingEdge(char a, char b) { return false; };

private:
    set<Node> nodes;
    set<Node>::iterator it;
    set<char>::iterator it2;
};

int main()
{
    return 0;
}

推荐答案

是迭代器给我带来了问题吗?

Is the iterator the one giving me the issue here?

不,而是 std::set 缺少自定义比较器导致了问题.意思是,编译器必须知道,如何对 Nodestd::set 进行排序.通过提供合适的 operator<,您可以修复它.请参阅此处的演示

No, rather the lack of custom comparator for std::set<Node> causes the problem. Meaning, the compiler has to know, how to sort the std::set of Node s. By providing a suitable operator<, you could fix it. See demo here

struct Node {
   char vertex;
   set<char> adjacent;

   bool operator<(const Node& rhs) const noexcept
   {
      // logic here
      return this->vertex < rhs.vertex; // for example
   }
};

<小时>

或提供自定义比较函子

struct Compare final
{
   bool operator()(const Node& lhs, const Node& rhs) const noexcept
   {
      return lhs.vertex < rhs.vertex; // comparision logic
   }
};
// convenience type
using MyNodeSet = std::set<Node, Compare>;

// types
MyNodeSet nodes;
MyNodeSet::iterator it;

这篇关于C2676:二进制“&lt;":“const _Ty"未定义此运算符或转换为预定义运算符可接受的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:C2676:二进制“&lt;":“const _Ty"未定义此运算符或转换为预定义运算符可接受的类型

基础教程推荐