C2676:二进制'<':'const _Ty'没有定义此运算符或未转换为预定义运算符可接受的类型 [英] C2676: binary '<': 'const _Ty' does not define this operator or a conversion to a type acceptable to the predefined operator

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

问题描述

对于以下代码,我一直收到此错误.

I keep getting this error for the code below.

阅读后,我认为我的错误是我的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<Node>的自定义比较器会导致此问题.意思是,编译器必须知道如何对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'没有定义此运算符或未转换为预定义运算符可接受的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆