通过引用将图形(列表列表)作为参数传递,我想将元素添加到仅在此函数内使用的每个列表中

时间:2015-10-02 21:30:09

标签: c++ graph

我有一个函数接收一个有向图,表示为需要执行此操作的列表列表:

int Algo::test(const vector<vector<int> > &graph) {
    ...
    // Add a few edges to the graph
    // Do calculations based on the graph
}

我可能会也可能不会使用const

要使此功能起作用,我需要在图形中添加一些其他边缘(需要确保每个边[v,w]都有[w,v])。我永远不会删除任何东西,只是添加,我不会重新排序边缘,因此每个新边缘都应该附加在各自列表的末尾。在此函数结束时,图形应保持其初始状态。

我想到了两种明显的方法:

(1)使用const并复制图表:

vector<vector<int> > graph2(graph);
// Work on graph2

(2)不要使用const,保存原始图表中每个列表的当前大小,修改它,最后删除添加的元素:

vector<unsigned> origSizes(graph.size());
for (unsigned i = 0; i < graph.size(); i++) 
    origSizes[i] = graph[i].size();

// Create edges and do calculations

for (unsigned i = 0; i < graph.size(); i++) 
    graph[i].erase(graph[i].begin() + origSizes[i], graph[i].end();

我不喜欢解决方案(1),因为复制整个图形似乎对我来说太多开销(图形可能很大)。我不喜欢解决方案(2),因为我更喜欢使用const而不是在内部修改原始图。

有没有比这两个选项更有效和/或更安全的其他替代方式?

1 个答案:

答案 0 :(得分:0)

您可以使用自己的数据结构扩充图表:

int Algo::test(const vector<vector<int> > &graph) {
    vector<vector<int> > extra_edges(graph.size());
    // Add the edges to extra_edges
    // Do stuff using both extra_edges and graph
    ...
}

将您需要的边缘添加到extra_edges。当您实际进行计算时,请务必检查两者原始边缘以及您通过extra_edges自行添加的边缘。

缺点是它使代码变得更复杂,但这是除了复制一切之外最不具侵入性的方法。