问题
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