在下面的代码中,
[id, name]
是一个const引用。然而,studentMap 是非常量的。用户可以在循环中更改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;
}
不,我认为不可能更改变量的类型。
如果你想避免修改
studentMap
的意外错误,你可以将逻辑放入一个单独的函数中,并使用 const ref 来引用 studentMap
:
#include <iostream>
#include <string>
#include <map>
void displayStudentMap(const auto& studentMap) {
for (const auto& [id, name] : studentMap) {
// compilation error
studentMap.at(id) += "test";
}
for (const auto& [id, name]: studentMap) {
std::cout << id << " " << name << "\n";
}
}
int main() {
std::map<int, std::string> studentMap;
studentMap[1] = "Tom";
studentMap[7] = "Jack";
studentMap[15] = "John";
displayStudentMap(studentMap);
}
这样:
const std::map<int, std::string> studentMap {
std::make_pair(1, "Tom"),
std::make_pair(7, "Jack"),
std::make_pair(15, "John")
};
或者使用 C++11 统一初始化:
const std::map<int, std::string> studentMap {
{ 1, "Tom" },
{ 7, "Jack" },
{ 15, "John" }
};