引用STL映射元素的值?
可以将映射元素值的引用传递给函数并在那里修改它吗?
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?
谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
答案是肯定的。
(运算符 [] 返回引用)
The answer is Yes.
(operator [] returns a reference)
我们可以。
它也适用于
std::vectors
(并且由于看起来您正在使用数字键,因此您可以考虑使用它们)。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).是的。
这与输入 m[1] = "xyz" 没有什么不同。 编译器完成后会将其简化为大致相同的内容。
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.
建议:您可能希望将其作为指针而不是引用传递。 我这样做是为了让普通读者更清楚地知道它将被改变。
这一切都是为了与下一个必须维护此代码的人进行清晰的沟通。
但除此之外,是的,它是完全合法的代码!
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!
是的,这很好 - 正如每个人都已经说过的 - 而且,您的编译器会告诉您是否不是。 您可能想尝试一下; 尝试将“hello”或 (42) 传递给 foo(string&) 以了解编译器给您的警告。
Yes, it's fine - as everyone already said- and furthermore, your compiler will tell you if it isn't. You may want to experiment a bit; try passing "hello" or (42) to foo(string&) to get a feeling for the warnings your compiler gives you.