【问题标题】:C2676: binary '<': 'const _Ty' does not define this operator or a conversion to a type acceptable to the predefined operatorC2676:二进制“<”:“const _Ty”未定义此运算符或转换为预定义运算符可接受的类型
【发布时间】:2020-08-10 19:09:05
【问题描述】:

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

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

【问题讨论】:

  • 链接是关于operator+,但是你在你的迭代器上使用operator++,细节很重要。无论如何,每个迭代器都有 operator++ 但您的问题与迭代器完全无关。正如错误所说,这是关于operator&lt;。`

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


【解决方案1】:

是迭代器给我的问题吗?

不,而是std::set&lt;Node&gt; 缺少自定义比较器导致问题。这意味着,编译器必须知道如何对Nodestd::set 进行排序。通过提供合适的operator&lt;,您可以修复它。见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;

【讨论】:

    猜你喜欢
    • 2021-02-14
    • 1970-01-01
    • 2021-04-05
    • 1970-01-01
    • 2021-06-11
    • 2020-10-10
    • 1970-01-01
    • 2021-11-30
    • 2020-12-09
    相关资源
    最近更新 更多