你的描述告訴我,你很可能尋找一個圖形表示。
你可以在這裏使用升壓圖:
Live On Coliru
#include <boost/graph/adjacency_list.hpp>
#include <boost/range.hpp> // make_iterator_range
#include <iostream>
#include <iomanip> // for std::setw
using namespace boost;
struct MyObj{
int idNumber;
};
typedef adjacency_list<vecS, vecS, bidirectionalS, MyObj> Graph;
int main() {
Graph g;
Graph::vertex_descriptor // essentially, index into the vector of MyObj
node1 = add_vertex(MyObj {42}, g),
node2 = add_vertex(MyObj { 7}, g),
node3 = add_vertex(MyObj {99}, g),
node4 = add_vertex(MyObj {-1}, g);
std::cout << "node1: " << node1 << "\n"; // 0
std::cout << "node2: " << node2 << "\n"; // 1
std::cout << "node3: " << node3 << "\n"; // 2
std::cout << "node4: " << node4 << "\n"; // 3
add_edge(node1, node3, g);
add_edge(node2, node3, g);
add_edge(node4, node1, g);
// now we have a graph with these connections:
for(auto const& connection: make_iterator_range(edges(g)))
{
Graph::vertex_descriptor sd = source(connection, g);
Graph::vertex_descriptor td = target(connection, g);
MyObj const& s = g[sd];
MyObj const& t = g[td];
std::cout << "Connection of " << sd << " (idNumber=" << std::setw(2) << s.idNumber << ") <-> "
<< td << " (idNumber=" << std::setw(2) << t.idNumber << ")\n";
}
}
輸出:
node1: 0
node2: 1
node3: 2
node4: 3
Connection of 0 (idNumber=42) <-> 2 (idNumber=99)
Connection of 1 (idNumber= 7) <-> 2 (idNumber=99)
Connection of 3 (idNumber=-1) <-> 0 (idNumber=42)
加快步伐可能一個對象連接到其他幾個對象?你需要雙向參考(5 - > 7,7 - > 5)還是隻有一個方向(5 - > 7)? – 2014-12-04 10:16:50
雙向引用,是的一個對象可以連接幾個ebjects! – 2014-12-04 10:20:05
您的約束條件太緊張,您的要求太短。您將無法將有效的指針或迭代器存儲到向量的元素中(除非您保證此向量永遠不會增長),我也不會建議嘗試這樣做。你不能存儲索引?或者其他一些獨特的索引?然後使用地圖而不是矢量?所有相當腥...... – 2014-12-04 10:30:42