Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

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

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...