在 C++11 之前启动容器类成员的简单方法
Easy way to initilize a container class member before C++11?
首先看到链接: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);
随意使用您最喜欢的数组成员计数技术,而不是魔术值。
相关文章:
- 引用基类模板的成员变量的简单方法
- 返回值的简单模板类成员函数专用化
- 通过此指针访问时的成员差异和自身的成员指针(简单的 QT 示例问题)
- 怎么能用memcpy复制工会简单的成员?
- 为什么 SFINAE 在这个简单的成员函数重载中不起作用
- 简单,但找不到:使用类型类的 STL 队列的成员变量的语法
- 使用并集的简单结构中的成员变量别名
- 我应该在简单的访问成员函数中使用 const 返回类型吗?
- 创建返回对象引用的成员函数的最简单方法
- 比较来自同一类型的两个对象的数据成员的最简单方法
- 遍历对类成员的引用,简单且最好是可重用的
- 在 C++11 中选择性地禁用模板成员的简单方法
- 在 C++11 之前启动容器类成员的简单方法
- 简单的 Java 代码,在创建等效C++(私有静态成员和公共访问器方法)时遇到问题
- 是否有一种简单的方法来初始化c++中的动态数组数据成员?
- 方法内部的简单c++成员引用(方法解析后的链接器错误)
- 存储抽象成员,保持接口简单
- (简单?)指针指向非静态成员函数的问题
- 打印成员函数地址的最简单方法是什么?
- 对传递给模拟函数的参数调用成员函数的最简单方法是什么?