先看链接:http://www.redblobgames.com/pathfinding/a-star/implementation.html
我正在尝试将 A* 的 C++11 代码重写为旧的 C++ 标准,您将如何以优雅的方式使用最少的拷贝编写图的初始化?
编辑: 如果您不喜欢下面示例中的非标准 hash_map,请忽略它并将其替换为 std::map。
#include <queue>
#include <hash_map>
using namespace std;
template<typename Loc>
struct Graph {
typedef Loc Location;
typedef typename vector<Location>::iterator iterator;
std::hash_map<Location, vector<Location> > edges;
inline const vector<Location> neighbors(Location id) {
return edges[id];
}
};
int main()
{
// C++11 syntax that needs to be rewritten
Graph<char> example_graph = {{
{'A', {'B'}},
{'B', {'A', 'C', 'D'}},
{'C', {'A'}},
{'D', {'E', 'A'}},
{'E', {'B'}}
}};
return 0;
}
我想要这样的东西:
Graph<char> example_graph;
...
example_graph.addEdge(edge, edge_neighbors_vector) // Pass a vector to initialize the other vector, that means copying from one vector to the other... is there a better way?
// OR
example_graph.addEdge(pair) // pair of edge and neighbors?
也许可变参数列表?
最佳答案
您可以定义一个辅助结构来捕获图中的节点信息。它就像一对,但允许您关联任意邻居。
template<typename Loc>
struct Node : pair<Loc, vector<Loc> > {
Node (Loc l) { pair<Loc, vector<Loc> >::first = l; }
Node & operator << (Loc n) {
pair<Loc, vector<Loc> >::second.push_back(n);
return *this;
}
};
然后,假设您已经为图形定义了一个构造函数,它将迭代器传递给底层映射,您可以执行类似这样的操作来定义节点数组:
Node<char> graph_init[] = {
Node<char>('A') << 'B',
Node<char>('B') << 'A' << 'C' << 'D',
Node<char>('C') << 'A',
Node<char>('D') << 'E' << 'A',
Node<char>('E') << 'B',
};
Graph<char> example_graph(graph_init, graph_init + 5);
请随意使用您最喜欢的数组成员计数技术,而不是魔法值。
关于c++ - 在 C++11 之前初始化容器类成员的简单方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35601749/