如何在c++中引用对象用于范围循环
在以下代码中,[id,name]
是const引用。但是,StudentMap是非const的。用户可以更改循环中StudentMap的值。 我想问是否有一种方法可以使StudentMap也可以进行const。谢谢。
#include <iostream>
#include <string>
#include <map>
int main() {
std::map<int, std::string> studentMap;
studentMap[1] = "Tom";
studentMap[7] = "Jack";
studentMap[15] = "John";
for (const auto& [id, name] : studentMap) {
studentMap.at(id) += "test";
}
for (const auto& [id, name]: studentMap) {
std::cout << id << " " << name << "\n";
}
return 0;
}
In the following code, [id, name]
is a const reference. However, studentMap is non-const. The user can change the value of studentMap in the loop.
I want to ask whether there is a way to make the StudentMap also const. Thanks.
#include <iostream>
#include <string>
#include <map>
int main() {
std::map<int, std::string> studentMap;
studentMap[1] = "Tom";
studentMap[7] = "Jack";
studentMap[15] = "John";
for (const auto& [id, name] : studentMap) {
studentMap.at(id) += "test";
}
for (const auto& [id, name]: studentMap) {
std::cout << id << " " << name << "\n";
}
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,我认为不可能更改变量的类型。
如果要避免修改
StudentMap
的意外错误,则可以将逻辑拉到单独的功能中,并使用const Ref参考studentmap
。No I don't think it is possible to change the type of a variable.
If you want to avoid unexpected mistake of modifying
studentMap
, you could pull the logic into a separate function, and referstudentMap
with a const ref:这样:
或使用C ++ 11均匀初始化:
This way:
or this with C++11 uniform initialization: