C++11 auto的用法

本文详细介绍了C++中range-based for循环的使用方法,包括如何遍历数组、字符串、vector和map等数据结构。同时,对比了引用与非引用在循环中的不同行为,展示了如何通过引用修改容器内的元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

auto表示挨个遍历元素

#include <iostream>
#include<vector>
#include<map>
using namespace std;
int main()
{
    int array[] = {1, 2, 3, 4, 5};
    for(auto e : array)
        cout << e << " ";
    cout<<endl;
    string str = "hello world";
    for(auto ch : str)
       cout << ch <<" ";
    cout<<endl;
    vector<int> m_v = {1, 2, 3, 4};
    for(auto e : m_v)
        cout << e <<" ";
    cout<<endl;
    map<int,string> m = {{1, "abc"}, {2, "bca"}, {3, "cab"}};
    for(auto e : m)
        cout <<e.first<<"  "<< e.second<<" ";
    cout<<endl;
    return 0;
}

输出如下:
1 2 3 4 5
h e l l o w o r l d
1 2 3 4
1 abc 2 bca 3 cab

for(auto &i:s)和for(auto i:s)的区别
前者不改变s的值,后者改变s的值(引用)

#include<iostream>
using namespace std;

int main()
{
	string s("hello world");
	for(auto c:s)
	c='t';
	cout<<s<<endl;//结果为hello world
	
	for(auto &c:s)
	c='t';
	cout<<s<<endl; //结果为ttttttttttt
}

输出:
hello world
ttttttttttt

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值