Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference to value of STL map element?

Tags:

c++

map

stl

Is it OK to pass to function a reference to the value of map element, and to modify it there?

foo(string & s)
{
    s = "xyz";
}

map<int, string> m;
m[1] = "abc";
foo(m[1]); // <-- Is it ok? Will m[1] be "xyz" after this call?

Thank you.

like image 793
Igor Avatar asked Feb 15 '09 13:02

Igor


4 Answers

The answer is Yes.

(operator [] returns a reference)

like image 123
Assaf Lavie Avatar answered Oct 06 '22 17:10

Assaf Lavie


Yes, we can.
And it also works with std::vectors (and since it looks like you're using numeric keys, you may consider using them instead).

like image 37
tunnuz Avatar answered Oct 06 '22 19:10

tunnuz


Yes.

This is no different to typing m[1] = "xyz". The compiler will reduce it all to about the same thing once its finished with it.

like image 41
Scott Langham Avatar answered Oct 06 '22 17:10

Scott Langham


A word of advice: You might want to pass it as a pointer rather than a reference. I do that to make it more obvious to the casual reader that it will be changed.

It's all about communicating clearly with the next guy comming down the pike, who has to maintain this code.

But other than that, yeah, it's completely legal code!

like image 45
Mr.Ree Avatar answered Oct 06 '22 19:10

Mr.Ree