mla*_*lai 1 c++ iterator graph c++-standard-library stdset
对于下面的代码,我不断收到此错误。
在阅读此,我相信我的错误是it++在我的for循环,我试图与更换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;
}
Run Code Online (Sandbox Code Playgroud)
迭代器是给我问题的那个吗?
不,而是缺少自定义比较器std::set<Node>导致问题。这意味着,编译器必须知道,如何排序std::set的Node秒。通过提供合适的operator<,您可以修复它。在这里查看演示
struct Node {
char vertex;
set<char> adjacent;
bool operator<(const Node& rhs) const noexcept
{
// logic here
return this->vertex < rhs.vertex; // for example
}
};
Run Code Online (Sandbox Code Playgroud)
或者提供一个自定义的比较函子
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;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4120 次 |
| 最近记录: |