引用STL映射元素的值?

发布于 2024-07-13 15:09:33 字数 219 浏览 5 评论 0原文

可以将映射元素值的引用传递给函数并在那里修改它吗?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

遗弃M 2024-07-20 15:09:34

答案是肯定的。

(运算符 [] 返回引用

The answer is Yes.

(operator [] returns a reference)

下壹個目標 2024-07-20 15:09:34

我们可以。
它也适用于 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).

溇涏 2024-07-20 15:09:34

是的。

这与输入 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.

信愁 2024-07-20 15:09:34

建议:您可能希望将其作为指针而不是引用传递。 我这样做是为了让普通读者更清楚地知道它将被改变。

这一切都是为了与下一个必须维护此代码的人进行清晰的沟通。

但除此之外,是的,它是完全合法的代码!

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!

浮生未歇 2024-07-20 15:09:34

是的,这很好 - 正如每个人都已经说过的 - 而且,您的编译器会告诉您是否不是。 您可能想尝试一下; 尝试将“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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文