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

标签 c++ graph iterator c++-standard-library stdset

我不断收到以下代码的错误。

阅读后this ,我认为我的错误是我的 for 循环中的 it++,我尝试用 next(it, 1) 替换它,但它没有解决我的问题。

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

#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> 的自定义比较器 |导致问题。意思是,编译器必须知道如何对 std::set 进行排序的 Node秒。通过提供合适的 operator< ,你可以修复它。参见 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
   }
};

或提供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;

关于c++ - C2676 : binary '<' : 'const _Ty' does not define this operator or a conversion to a type acceptable to the predefined operator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61455321/

相关文章:

python - Neo4J 通过索引中节点的最短路径

java - 哈希集迭代

python - NetworkX:检查两个图是否具有相同的形状和相同的节点属性

c++ - 检查元组类型是否是彼此的子集

c++ - 指向存储在 uint64_t 中的内存位置的指针

c++ - 使用strtok按条件拆分字符串?

graph - 绘制深度优先搜索树

python - 如何控制python中迭代器结果的顺序

Java - ListIterator 和 hasNext

c++ - 表格的STL容器