【C++基础知识——迭代器 引入】

问题引入

#include <iostream>
#include <map>
#include <string>

int main() {
    // 定义一个 std::map 容器
    std::map<std::string, int> ageMap;
    ageMap["Alice"] = 30;
    ageMap["Bob"] = 25;
    ageMap["Charlie"] = 35;

    // 使用迭代器遍历并修改容器中的元素
    for (auto it = ageMap.begin(); it != ageMap.end(); ++it) {
        std::cout << it->first << " is " << it->second << " years old." << std::endl;

        // 修改元素的值
        it->second += 1;
    }

    std::cout << "After incrementing ages:" << std::endl;

    // 再次使用迭代器遍历容器,打印修改后的值
    for (auto it = ageMap.begin(); it != ageMap.end(); ++it) {
        std::cout << it->first << " is now " << it->second << " years old." << std::endl;
    }

    return 0;
}

输出结果:

Alice is 30 years old.
Bob is 25 years old.
Charlie is 35 years old.
After incrementing ages:
Alice is now 31 years old.
Bob is now 26 years old.
Charlie is now 36 years old.

**问题**:这里的it 到底是引用还是拷贝?如果是拷贝,为什么对于拷贝的内容设置了之后会生效?

问题回答

  • 在这个函数中,it 是一个迭代器,不是引用也不是拷贝。迭代器本身是一个轻量级对象,通常包含指向容器元素的指针或类似的结构。通过迭代器访问和修改容器中的元素是有效的。

  • 迭代器是指向容器元素的指针或类似结构,通过迭代器可以访问和修改容器中的元素。因此,it 不是对元素的拷贝,而是指向元素的一个指针或类似结构。通过迭代器修改元素是有效的,修改会反映在原始容器中。

代码解释

  1. 定义 std::map 容器:

    • std::map<std::string, int> ageMap; 定义一个 std::map 容器,键为 std::string 类型,值为 int 类型。
    • ageMap[“Alice”] = 30; 等语句向容器中插入元素。
  2. 使用迭代器遍历并修改容器中的元素:

    • for (auto it = ageMap.begin(); it != ageMap.end(); ++it) 使用迭代器遍历 ageMap 容器。
    • std::cout << it->first << " is " << it->second << " years old." << std::endl; 打印每个元素的键和值。
    • it->second += 1; 修改每个元素的值,将年龄加 1。
  3. 再次使用迭代器遍历容器,打印修改后的值:

    • 再次使用迭代器遍历 ageMap 容器,打印修改后的值。

总结

it 是一个迭代器,不是引用也不是拷贝。通过迭代器 it 修改容器中的元素是有效的,修改会反映在原始容器。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值