这并不是一个高效的实现,但也许一组键值对正是你所需要的。
#include <iostream>
#include <utility>
#include <set>
#include <algorithm>
template<class T>
class graph
{
public:
std::set<std::pair<T, T>> storage;
bool add_edge(T v1, T v2)
{
auto ret = storage.insert(std::make_pair(v1, v2));
return ret.second;
}
int delete_edge(T v1, T v2)
{
return storage.erase(std::make_pair(v1, v2));
}
void print_graph()
{
std::for_each(storage.begin(), storage.end(),
[](std::pair<T, T> const& p) {
std::cout << p.first << "--> " << p.second << std::endl;
});
}
};
#include <iostream>
#include "graph.h"
int main()
{
graph<int> g;
g.add_edge(5, 4);
g.add_edge(5, 4);
g.add_edge(6, 2);
g.print_graph();
g.delete_edge(5, 4);
g.print_graph();
return 0;
}
编译命令
g++ -std=c++17 -Wall -Wextra -pedantic main.cpp
输出
5 --> 4
6 --> 2
/* Deleted 5 --> 4 */
6 --> 2
adj
传递给函数时遇到了什么问题?像所有数组一样,它很容易衰减为指向其第一个元素的指针。 - Some programmer dudestd::array
),请用动态容器(std::vector
)替换它们。 - Jarod42