C++ 遍历循环语句 for(auto i:) 和 for_each()

传统for语句:

    int a[8]={1,1,2,3,5,8,13,21};
    for (int i=0;i<8;i++) cout<<a[i];

一般形式:for (单次表达式;条件表达式;末尾循环体) {中间循环体;}

对条件已知递增为1的可用遍历形式: for ( int i:a) cout<<a[i];

这里的int i并非i是整型变量,而是a[]的类型,如它是一个string数组:

    string b[3]={"a","ab","abc"};
    for (string i:b) cout<<i;

遍历for语句:

    int a[8]={1,1,2,3,5,8,13,21};
    string b[3]={"a","ab","abc"};
    for (auto i:a) cout<<i;
    for (auto i:b) cout<<i;

引入关键字 auto 后,就不用管变量类型了,自动的。

嵌套for (auto)列印一个乘法口诀表:

#include <iostream>
#include <array>
using namespace std;
int main(void)
{
	int i=0;
	array<int,9>a,b;  //其实只要一个数组就能实现,见下一段代码
	for (auto&c:a) c=++i;
	for (auto&c:b) c=10-i--;
	for (auto c:a){
		for (auto d:b) if (c>=d) cout<<d<<"x"<<c<<"="<<c*d<<"\t";
		cout<<endl;
	}
	return 0;
}

输出结果:

1x1=1
1x2=2   2x2=4
1x3=3   2x3=6   3x3=9
1x4=4   2x4=8   3x4=12  4x4=16
1x5=5   2x5=10  3x5=15  4x5=20  5x5=25
1x6=6   2x6=12  3x6=18  4x6=24  5x6=30  6x6=36
1x7=7   2x7=14  3x7=21  4x7=28  5x7=35  6x7=42  7x7=49
1x8=8   2x8=16  3x8=24  4x8=32  5x8=40  6x8=48  7x8=56  8x8=64
1x9=9   2x9=18  3x9=27  4x9=36  5x9=45  6x9=54  7x9=63  8x9=72  9x9=81

--------------------------------
Process exited after 0.8755 seconds with return value 0
请按任意键继续. . .

vector容器也一样:

/* Written by Yang Cheng, 2021.1.29 */

#include <iostream>
#include <vector> 
using namespace std;
int main(void)
{
	int i=0;
	vector<int>a(9);
	for (auto&b:a) b=++i;
	for (auto b:a){
		for (auto c:a) if (b>=c) cout<<c<<"x"<<b<<"="<<b*c<<"\t";
		cout<<endl;
	}
	return 0;
}

二维数组的赋值和列印:

#include <iostream>
#include <iomanip>
using namespace std;

int main(void)
{
	int arr[9][9];
	int i=0;
	for(auto &row:arr)
        for(auto &col:row)
            col=++i;

 	for(auto &a:arr){
        for(auto b:a)
            cout<<setw(3)<<b;
        cout<<endl;
    }
    
    return 0;
}

输出结果:

E:\>test2
  1  2  3  4  5  6  7  8  9
 10 11 12 13 14 15 16 17 18
 19 20 21 22 23 24 25 26 27
 28 29 30 31 32 33 34 35 36
 37 38 39 40 41 42 43 44 45
 46 47 48 49 50 51 52 53 54
 55 56 57 58 59 60 61 62 63
 64 65 66 67 68 69 70 71 72
 73 74 75 76 77 78 79 80 81

E:\>

迭代器iterator遍历:

#include <iostream>
#include <array>
using namespace std;
 
int main(void)
{
	array<int,8>a={2,3,4,5,6,7,8,9};
	
	array<int,8>::iterator it=a.begin();  //声明一个迭代器
	for(;it<a.end();++it) cout<<*it<<" ";  //相当于指针,*it表示迭代器当前指向的元素
	cout<<endl;
	
	for(array<int,8>::iterator it=a.begin();it<a.end();++it) *it*=2; //所有元素倍增
	cout<<endl;              //也可以写成一行,此迭代器为循环体变量,与循环体外的it无关
	
	for(auto it=a.begin();it<a.end();++it) cout<<*it<<" ";  //建议用auto关键字声明
	cout<<endl;

    return 0;
}

/*
运行结果:

2 3 4 5 6 7 8 9

4 6 8 10 12 14 16 18

--------------------------------
Process exited after 0.4409 seconds with return value 0
请按任意键继续. . .
*/

for_each() 遍历:

for_each()不像for (auto)是C++循环结构语句中的的一种形式。

  std::for_each(.,.,.)  //只是用using namespace std; 省掉了std::

它通常被用于容器(或称向量类型)vector的遍历,要引用头文件:
#include <algorithm>

详情见以下代码:

#include <iostream>
#include <iomanip>
#include <string>
#include <regex>
#include <vector>

using namespace std;

void mycout(int n)
{
	cout<<setw(3)<<n;
}

int ichange(int &n) //引用传递&n 否则实参不随形参变动 
{
	n=n*2+1;
	return n;
}

int main(void)
{
	int a[8]={1,1,2,3,5,8,13,21};
	for (auto i:a) mycout(i); //列印出数组a 
	cout<<endl;
	
	int arraysize=sizeof(a)/sizeof(int);
	vector<int> b(a,a+arraysize); //把数组a所有元素的值赋给容器b的各元素
    for_each(b.begin(),b.end(),ichange); //调用函数改变容器b各元素的值 
    cout<<endl;
    
	for (auto i:b) cout<<setw(3)<<i; //列印出容器b 
    cout<<endl;
}

输出结果:

E:\>test1
  1  1  2  3  5  8 13 21

  3  3  5  7 11 17 27 43

E:\>

关于vector的说明:

1. vector:

1.1 vector 说明

vector是向量类型,可以容纳许多类型的数据,因此也被称为容器(可以理解为动态数组,是封装好了的类)
进行vector操作前应添加头文件#include <vector>

1.2 vector初始化:

方式1.

//定义具有10个整型元素的向量(尖括号为元素类型名,它可以是任何合法的数据类型),不具有初值,其值不确定
vector<int>a(10);

方式2.

//定义具有10个整型元素的向量,且给出的每个元素初值为1
vector<int>a(10,1);

方式3.

//用向量b给向量a赋值,a的值完全等价于b的值
vector<int>a(b);

方式4.

//将向量b中从0-2(共三个)的元素赋值给a,a的类型为int型
vector<int>a(b.begin(),b.begin+3);

方式5.

 //从数组中获得初值
int b[7]={1,2,3,4,5,6,7};
vector<int> a(b,b+7);


1.3 vector对象的常用内置函数使用(举例说明)

#include<vector>
vector<int> a,b;
//b为向量,将b的0-2个元素赋值给向量a
a.assign(b.begin(),b.begin()+3);
//a含有4个值为2的元素
a.assign(4,2);
//返回a的最后一个元素
a.back();
//返回a的第一个元素
a.front();
//返回a的第i元素,当且仅当a存在
a[i];
//清空a中的元素
a.clear();
//判断a是否为空,空则返回true,非空则返回false
a.empty();
//删除a向量的最后一个元素
a.pop_back();
//删除a中第一个(从第0个算起)到第二个元素,也就是说删除的元素从a.begin()+1算起(包括它)一直到a.begin()+3(不包括它)结束
a.erase(a.begin()+1,a.begin()+3);
//在a的最后一个向量后插入一个元素,其值为5
a.push_back(5);
//在a的第一个元素(从第0个算起)位置插入数值5,
a.insert(a.begin()+1,5);
//在a的第一个元素(从第0个算起)位置插入3个数,其值都为5
a.insert(a.begin()+1,3,5);
//b为数组,在a的第一个元素(从第0个元素算起)的位置插入b的第三个元素到第5个元素(不包括b+6)
a.insert(a.begin()+1,b+3,b+6);
//返回a中元素的个数
a.size();
//返回a在内存中总共可以容纳的元素个数
a.capacity();
//将a的现有元素个数调整至10个,多则删,少则补,其值随机
a.resize(10);
//将a的现有元素个数调整至10个,多则删,少则补,其值为2
a.resize(10,2);
//将a的容量扩充至100,
a.reserve(100);
//b为向量,将a中的元素和b中的元素整体交换
a.swap(b);
//b为向量,向量的比较操作还有 != >= > <= <
a==b;


2. 顺序访问vector的几种方式,举例说明

2.1. 对向量a添加元素的几种方式

1.向向量a中添加元素

vector<int>a;
for(int i=0;i<10;++i){a.push_back(i);}

2.从数组中选择元素向向量中添加

int a[6]={1,2,3,4,5,6};
vector<int> b;
for(int i=0;i<=4;++i){b.push_back(a[i]);}

3.从现有向量中选择元素向向量中添加

int a[6]={1,2,3,4,5,6};
vector<int>b;
vector<int>c(a,a+4);
for(vector<int>::iterator it=c.begin();it<c.end();++it)
{
	b.push_back(*it);
}

4.从文件中读取元素向向量中添加

ifstream in("data.txt");
vector<int>a;
for(int i;in>>i){a.push_back(i);}

5.常见错误赋值方式

vector<int>a;
for(int i=0;i<10;++i){a[i]=i;}//下标只能用来获取已经存在的元素


2.2 从向量中读取元素

1.通过下标方式获取

int a[6]={1,2,3,4,5,6};
vector<int>b(a,a+4);
for(int i=0;i<=b.size()-1;++i){cout<<b[i]<<endl;}


2.通过迭代器方式读取

 int a[6]={1,2,3,4,5,6};
 vector<int>b(a,a+4);
 for(vector<int>::iterator it=b.begin();it!=b.end();it++){cout<<*it<<"  ";}


3.几个常用的算法

#include<algorithm>

 //对a中的从a.begin()(包括它)到a.end()(不包括它)的元素进行从小到大排列
sort(a.begin(),a.end());

 //对a中的从a.begin()(包括它)到a.end()(不包括它)的元素倒置,但不排列,如a中元素为1,3,2,4,倒置后为4,2,3,1
reverse(a.begin(),a.end());

  //把a中的从a.begin()(包括它)到a.end()(不包括它)的元素复制到b中,从b.begin()+1的位置(包括它)开始复制,覆盖掉原有元素
 copy(a.begin(),a.end(),b.begin()+1);

 //在a中的从a.begin()(包括它)到a.end()(不包括它)的元素中查找10,若存在返回其在向量中的位置
find(a.begin(),a.end(),10);

以上关于vector的说明引用自:https://blog.csdn.net/weixin_41743247/article/details/90635931

  • 20
    点赞
  • 75
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
WARNINGS: ?: (staticfiles.W004) The directory 'static' in the STATICFILES_DIRS setting does not exist. buy.Cart: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'. HINT: Configure the DEFAULT_AUTO_FIELD setting or the BuyConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django.d b.models.BigAutoField'. buy.Orders: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'. HINT: Configure the DEFAULT_AUTO_FIELD setting or the BuyConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django.d b.models.BigAutoField'. sale.Brand: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'. HINT: Configure the DEFAULT_AUTO_FIELD setting or the SaleConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django. db.models.BigAutoField'. sale.Carinfo: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'. HINT: Configure the DEFAULT_AUTO_FIELD setting or the SaleConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django. db.models.BigAutoField'. userinfo.UserInfo: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'. HINT: Configure the DEFAULT_AUTO_FIELD setting or the UserinfoConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'dja ngo.db.models.BigAutoField'. No changes detected
06-02
The warnings indicate the following issues: - `staticfiles.W004`: The `STATICFILES_DIRS` setting is configured to use a directory named `static`, but it does not exist in your project. You should either create the directory or modify the setting to use an existing directory. - `models.W042`: Auto-created primary keys are being used for several of your models (`buy.Cart`, `buy.Orders`, `sale.Brand`, `sale.Carinfo`, `userinfo.UserInfo`). You should explicitly define a primary key field for each model instead of relying on the default auto-generated primary key. To do this, add a `primary_key=True` argument to a field in the model definition, or specify a custom primary key field using the `primary_key` attribute. - `No changes detected`: This is not a warning, but rather an informational message indicating that no changes were detected in your models that require migration. To address the `models.W042` warnings, you can either add a `primary_key=True` argument to an existing field or create a new field with the `primary_key=True` argument. For example: ```python class Cart(models.Model): cart_id = models.AutoField(primary_key=True) # ... ``` Alternatively, you can configure the `DEFAULT_AUTO_FIELD` setting in your project settings to specify a custom primary key field for all models in your project. For example: ```python # settings.py from django.conf import settings class BuyConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' settings.configure(BUY_CONFIG=BuyConfig) ``` This will set the default auto-generated primary key field for all models in the `buy` app to `BigAutoField`. You can repeat this pattern for other apps in your project as well.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Hann Yang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值