第五章 数组和循环
数组:可以储存相同类型的数据项
一般使用sizeof(nums)/ziseof(nums[0])来计算数组的元素个数
#include <iostream>
using namespace std;
int main()
{
int nums[10]; // int类型的数组,有10个元素
cout << nums[0] << endl; // 没有初始化,打印出来的是个奇怪的值
nums[0] = 1; // 第一个元素的索引是0,初始化为1
cout << nums[0] << endl;
int nums2[6]{ 1,2,3 }; // 前3个元素是1,2,3,后面3个元素是0
int nums3[7]{}; // 有7个元素,全是0
const int nums4[3]{ 91, 92, 93 }; // nums4的值不能进行修改
int nums5[] {1,2,3,4}; // nums5大小为4,根据后面元素个数自动编译
}
循环
for:为一个元素集合中每个元素执行一次迭代
while:只要特定条件为true,开始执行,如果开始为false,不执行
do-while:迭代结束时检查,至少执行一次
#include <iostream>
using namespace std;
int main()
{
// 利用循环,copy列表,然后打印
const int nums4[3]{ 91, 92, 93 }; // nums4的值不能进行修改
int nums4_copy[3];
for (int i = 0; i < 3; i++) {
nums4_copy[i] = nums4[i];
cout << nums4_copy[i] << endl;
}
}
在for循环中初始化多个变量
#include <iostream>
using namespace std;
int main()
{
for (int i{ 0 },j{ 0 }; (i < 10) && (j < 20); i++) {
j += i;
cout << "i = " << i << endl;
cout << "j = " << j << endl;
}
return 0;
}
基于范围的for循环
#include <iostream>
using namespace std;
int main()
{
int nums[5]{ 2,3,4,5,6 };
for (int i : nums) {
if (i > 4) {
cout << i << " ";
}
}
cout << endl;
}
while循环
#include <iostream>
using namespace std;
int main()
{
int nums[5]{ 2,3,4,5,6 };
int i{};
while (i < 4) {
cout << nums[i] << endl;
i++;
}
}
do-while循环
#include <iostream>
using namespace std;
int main()
{
int nums[5]{ 2,3,4,5,6 };
int i{};
do
{
cout << nums[i] << endl;
i++;
} while (i < 4);
}
continue:跳过当前循环,开始下一次循环
break:跳出整个循环
#include <iostream>
using namespace std;
int main()
{
while (true)
{
int n;
cout << "输入一个整数(输入0退出):";
cin >> n;
if (n == 0) {
break;
}
if (n > 10) {
cout << "大于10" << endl;
}
else {
cout << "小于10" << endl;
}
}
}
字符数组
#include <iostream>
using namespace std;
int main()
{
char a[]{'h','e','l','l','o'}; // 表示一个字符数组
cout << sizeof(a) / sizeof(a[0]) << endl; // 5
char b[]{ "hello" }; // 表示一个字符串
cout << sizeof(b) / sizeof(b[0]) << endl; // 6 末尾有个'\0'标记字符串结束
}
多维数组
#include <iostream>
using namespace std;
int main()
{
int s[3][4];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
s[i][j] = i + j;
cout << s[i][j] << " ";
}
cout << endl;
}
}
容器
数组array<T, N>:需要知道大小
向量vector<T>:可以不需要知道大小
#include <iostream>
#include <array>
using namespace std;
int main()
{
array<int, 10> nums{1,2,3,4,5,6,7,8,9,10};
for (int i = 0; i < nums.size(); i++) {
cout << nums[i] << endl;
}
}