c++ - Passing a graph (list of lists) as parameter by reference, I want to add elements to each list to be used inside this function only -


i have function receives directed graph represented list of lists needs this:

int algo::test(const vector<vector<int> > &graph) {     ...     // add few edges graph     // calculations based on graph } 

i may or may not use const.

for function work, need add few other edges graph (need make sure there [w,v] every edge [v,w]). i'll never remove anything, add, , not reorder edges, every new edge should appended @ end of respective list. @ end of function, graph should left in initial state.

i thought of 2 obvious ways this:

(1) use const , copy graph:

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

(2) not use const, save current size of each list in original graph, modify , in end erase added elements:

vector<unsigned> origsizes(graph.size()); (unsigned = 0; < graph.size(); i++)      origsizes[i] = graph[i].size();  // create edges , calculations  (unsigned = 0; < graph.size(); i++)      graph[i].erase(graph[i].begin() + origsizes[i], graph[i].end(); 

i don't solution (1) because copying entire graph seems overhead me (the graph may large). don't solution (2) because prefer use const , not modify original graph internally.

is there other alternative way more efficient and/or safer these 2 options?

you can augment graph using own data structure:

int algo::test(const vector<vector<int> > &graph) {     vector<vector<int> > extra_edges(graph.size());     // add edges extra_edges     // stuff using both extra_edges , graph     ... } 

add edges need extra_edges. when computation, sure check both original edges , ones you've added via extra_edges.

the downside makes code bit more complicated, however, least intrusive approach besides copying everything.


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -