C2676: binary '<': 'const _Ty' does not define this operator or a conversion to a type acceptable to the predefined operator

佐手、 提交于 2021-02-17 03:00:51

问题


I keep getting this error for the code below.

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;
}

回答1:


Is the iterator the one giving me the issue here?

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
   }
};

Or provide a custom compare functor

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;


来源:https://stackoverflow.com/questions/61455321/c2676-binary-const-ty-does-not-define-this-operator-or-a-conversion-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!