如何在 C++ for range 循环中 const 引用对象

问题描述 投票:0回答:2

在下面的代码中,

[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;
}
c++ stdmap
2个回答
3
投票

不,我认为不可能更改变量的类型。

如果你想避免修改

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

3
投票

这样:

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" }
};
© www.soinside.com 2019 - 2024. All rights reserved.