在上一次的头文件中再添加一个类-迭代器,可用作后面测试用例
稠密图迭代器代码
class adjIterator {
private:
DenseGraph& G;
int index;
int v;
public:
//构造函数
adjIterator(DenseGraph& g, int v):G(g) {
assert(v >= 0 && v < G.n);
this->v = v;
this->index = -1;
}
//析构函数
~adjIterator(){}
int begin() {
index = -1;
return next();
}
int next() {
for (index += 1; index < G.V(); index++) {
if (G.g[v][index])
return index;
}
return -1;
}
bool end() {
return index >= G.V();
}
};
稀疏图迭代器代码
class adjIterator {
private:
SparseGraph& G;
int v;
int index;
public:
adjIterator(SparseGraph& g, int v) :G(g) {
assert(v >= 0);
this->v = v;
this->index = 0;
}
~adjIterator(){}
int begin() {
index = 0;
if (G.g[v].size())
return G.g[v][index];
return -1;
}
int next() {
index++;
if (index < G.g[v].size())
return G.g[v][index];
return -1;
}
bool end() {
return index >= G.g[v].size();
}
};
测试用例,构建图
#include <iostream>
#include <time.h>
#include <stdlib.h>
#include "DenseGraph.h"
#include "SparseGraph.h"
using namespace std;
int main() {
//测试用例,20个顶点,70条边,无向图
int n = 20;
int m = 70;
bool directed = false;
//随机种子
srand(time(NULL));
DenseGraph DG(n, directed);
for (int i = 0; i < m; ++i) {
int v = rand() % n;
int w = rand() % n;
DG.addEdge(v, w);
}
//打印图
for (int i = 0; i < n; ++i) {
cout << i << ":";
DenseGraph::adjIterator adj(DG, i);
for (int it = adj.begin(); !adj.end(); it = adj.next())
cout << it << " ";
cout << endl;
}
//稀疏图,邻接表,
SparseGraph SG(n, m);
for (int i = 0; i < m; ++i) {
int v = rand() % n;
int w = rand() % n;
SG.addEdge(v,w);
}
//打印图
cout << "============分隔符================" << endl;
for (int i = 0; i < n; ++i) {
cout << i << ":";
SparseGraph::adjIterator adj(SG, i);
for (int it = adj.begin(); !adj.end(); it = adj.next()) {
cout << it << " ";
}
cout << endl;
}
system("pause");
return 0;
}
测试