Home > Enterprise >  How to const reference an object in the c for range loop
How to const reference an object in the c for range loop

Time:05-05

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;
}

CodePudding user response:

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 refer studentMap with a const ref:

#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);
}

CodePudding user response:

This way:

const std::map<int, std::string> studentMap {
    std::make_pair(1, "Tom"),
    std::make_pair(7, "Jack"),
    std::make_pair(15, "John")
};
  • Related