c++ - 在 C++11 之前初始化容器类成员的简单方法?

标签 c++

先看链接: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/

相关文章:

c++ - rapidXML,遍历 DOM 树时内存损坏

c++ - 无法解决循环依赖

c++ - 实例化后的显式特化

c++ - GCC 可以配置为忽略#pragma 指令吗?

c++ - Cocos2d-x : How can I draw a resizing rectangle?

C++:在包含的头文件中使用#define 常量 (Arduino)

C++使用递归查找Vector中非零的数量

c++ - 找出继承对象的类

c++ - 有人可以解释 openssl cli 和 c++ DES 输出的区别吗

c++ - 如何制作指针迭代器?