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;
}
studentMapto be non-const as you are setting that up before the loops. So, you could do something like creating a new scope (e.g. a new function), have a const ref referring tostudentMap, and iterate thru thatconstStudentMapconst auto& constStudentMap = studentMap;