C++11的for循环使用auto的新用法

本文介绍了C++11中使用`auto`关键字的新型for循环,展示了如何遍历不同类型的容器,如vector、数组、string和map,并通过`for_each`函数配合回调函数进行元素处理。示例代码详细解释了每种遍历方法,包括使用模板函数和迭代器的方式,加深了对C++11新特性的理解。
摘要由CSDN通过智能技术生成

C++11的for循环使用auto的新用法

for(auto a:vec)
{
cout<<a<<" ";
}

#include<bits/stdc++.h>
using namespace std;
int main()
{
	vector<int> vec;
	for(int i=0; i<10; i++)
	{
		vec.push_back(i);
	}


	for(auto a:vec)
	{
		cout<<a<<" ";
	}
    cout << endl;

    vector<int>::iterator it = vec.begin();
    for (it; it != vec.end();it++)
    {
        cout << *it << " ";
    }
        system("pause");
    return 0;
 } 

在这里插入图片描述

void printLN(T value)
{
cout << value <<" ";
}
for_each(vec.begin(), vec.end(), printLN);

for_each(iterator,iterator,callback);

前两个参数列表是遍历容器的迭代器,第三个参数是对应的回调函数

回调函数的原理都是将参数传递至相应的函数体,再进行操作

#include<bits/stdc++.h>
using namespace std;
template<typename T>
void printLN(T value)
{
    cout << value <<" ";
}
int main()
{
	vector<int> vec;
	for(int i=0; i<10; i++)
	{
		vec.push_back(i);
	}
    for_each(vec.begin(), vec.end(), printLN<int>);

        system("pause");
    return 0;
 } 

在这里插入图片描述

#include<bits/stdc++.h>
using namespace std;

int main()
{
    //array
    int array[] = {1, 2, 3, 4, 5};
    for(auto a:array)
    {
        cout << a << " ";
    }
    cout << endl;


    //string
    string str = "hello world!";
    for(auto b:str)
    {
        cout << b << " ";
    }
    cout << endl;


    //vector
    vector<int> vec = {1, 3, 5, 7};
    for(auto c:vec)
    {
        cout << c << " ";
    }
    cout << endl;


    //map
    map<int, string> mymap = {{1, "abc"}, {2, "bca"}, {3, "acb"}};
    for(auto d:mymap)
    {
        cout << d.first << " " << d.second << " ";
    }
    cout << endl;

    cout << "另一种方式:";

    for (map<int, string>::iterator it = mymap.begin(); it != mymap.end(); it++)
    {
        cout<< it->first<<" "<<it->second<< " ";
    }
    cout << endl;
    system("pause");

    return 0;
 } 

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值