1

Supposed I have a graph defined in such way,

unordered_map<int, unordered_set<int>> graph = {
    { 0, { 1, 2, 3 } },
    { 1, { 3, 4, 5 } },
    { 2, { 6, 5, 4 } }
};

And I want to empty the hash set of each entry in graph. I do two options here,

A. for(auto v = graph.begin(); v != graph.end(); ++v) v->second.clear();

B. for(auto v : graph) v.second.clear();

I see A works but B does not. I do not quite understand. My theory is, the way B is doing, v is a copy of the actual element. So it cannot clear the actual hash set.

Need help. Thanks!

2 Answers 2

4

My theory is, the way B is doing, v is a copy of the actual element

Your theory is correct.

Since you want to modify the original, iterate with a reference instead of a copy:

for(auto& v : graph) v.second.clear();
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, it works! And I have another question. According to my test, the running time of for(auto &v : graph) is longer than for(auto v : graph). I am confused here. The first way does not require making a copy of graph, v is just a reference. It will make more sense to me that the second one runs longer.
I see probably the longer time is due to the server is busier at the moment.
@CodingForFun15 Perhaps the compiler can deduce that clearing the temporary copies has no effect on the program, so it decides to remove the loop entirely.
@ user2079303 Make sense. Thanks!
0

If you are working exclusively on a Windows Platform and have VS2012 or newer this method is also available to use.

typedef unordered_map<int, unordered_set<int>> Graph;

Graph myGraph = {
    { 0, { 1, 2, 3 } },
    { 1, { 3, 4, 5 } },
    { 2, { 6, 5, 4 } }
};

for each ( Graph& graph in myGraph ) {
    // Do Work Here!
    graph.second.clear();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.