在 C++11 之前启动容器类成员的简单方法

Easy way to initilize a container class member before C++11?

本文关键字:成员 简单 方法 容器类 启动 C++11      更新时间:2023-10-16

首先看到链接: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);

随意使用您最喜欢的数组成员计数技术,而不是魔术值。