CSP-J初赛for(auto)用法
文章目录
- 基本格式
- 代码示例
- 数组
- 不执行写的操作
- 执行写的操作
- vector
- 不执行写的操作
- 执行写的操作
- 等价代码辅助理解
- 以下是两个等价的代码
- 代码1
- 代码2
基本格式
for(auto a : b)//代码
其中, bbb 表示的必须是一个序列,比如用大括号括起来的初始值列表、数组,或者vector或string类型的对象,这些类型的共同特点是拥有能返回迭代器的 beginbeginbegin 和 endendend 成员。
其中, aaa 定义一个变量序列中的每个元素都得能转换成该变量的类型。确保类型相容最简单的方法是使用auto类型说明符,这个关键字可以令编译器帮助我们指定合适的类型。(PS:如果需要对序列中的元素执行写的操作,循环变量必须声明成引用类型)
代码示例
数组
不执行写的操作
#include<bits/stdc++.h>
using namespace std;int main()
{int num[10] = {1,2,3};for(auto v : num)cout << v << " ";return 0;
}
//输出:1 2 3 0 0 0 0 0 0 0
执行写的操作
#include<bits/stdc++.h>
using namespace std;int main()
{int num[10] = {1,2,3};for(auto &v : num)v *= 2;for(auto v : num)cout << v << " ";return 0;
}
//输出:2 4 6 0 0 0 0 0 0 0
vector
不执行写的操作
#include<bits/stdc++.h>
using namespace std;int main()
{vector<int> num[10] = {1,2,3};for(auto v : num)cout << v << " ";return 0;
}
//输出:1 2 3
执行写的操作
#include<bits/stdc++.h>
using namespace std;int main()
{vector<int> num[10] = {1,2,3};for(auto &v : num)v *= 2;for(auto v : num)cout << v << " ";return 0;
}
//输出:2 4 6
等价代码辅助理解
以下是两个等价的代码
代码1
#include<bits/stdc++.h>
using namespace std;int main()
{vector<int> num[10] = {1,2,3};for(auto &v : num)v *= 2;for(auto v : num)cout << v << " ";return 0;
}
//输出:2 4 6
代码2
#include<bits/stdc++.h>
using namespace std;int main()
{vector<int> num[10] = {1,2,3};for(auto it = num.begin();it != num.end();++ it){auto &v = *it;v *= 2;}for(auto v : num)cout << v << " ";return 0;
}
//输出:2 4 6