首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在c++ for range循环中引用对象

如何在c++ for range循环中引用对象
EN

Stack Overflow用户
提问于 2022-05-04 19:28:46
回答 2查看 88关注 0票数 1

在下面的代码中,[id, name]是一个const引用。然而,studentMap是不连续的.用户可以在循环中更改studentMap的值。我想问一问是否有一种方法使StudentMap也const。谢谢。

代码语言:javascript
运行
AI代码解释
复制
#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;
}
EN

回答 2

Stack Overflow用户

发布于 2022-05-04 19:40:03

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

如果要避免修改studentMap这一意外错误,可以将逻辑提取到单独的函数中,并使用const引用studentMap

代码语言:javascript
运行
AI代码解释
复制
#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
EN

Stack Overflow用户

发布于 2022-05-05 00:59:52

这条路:

代码语言:javascript
运行
AI代码解释
复制
const std::map<int, std::string> studentMap {
    std::make_pair(1, "Tom"),
    std::make_pair(7, "Jack"),
    std::make_pair(15, "John")
};
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72121592

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档