我不断收到以下代码的错误。
阅读后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
}
};
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/