数组
c++11之循环遍历优化
格式:
for(变量类型 变量名:数组名)
- 这里的变量类型可填成员类型也可用auto类型
- 若类型不一致且可转换,默认进行强转
例子:
int Students[5]{}; //学号
int num = sizeof(Students) / sizeof(int);
for (int i = 0; i < num; ++i)
{
cout << "请输入第" << i + 1 << "个学生的学号:";
cin >> Students[i];
}
//for (int i : Students) //可以用这个
for (auto i : Students) //也可以用这个
{
cout << i << endl;
}
重温多维数组
二维数组遍历:
int students[3][3]
{
{1,2,3},
{4,5,6},
{7,8,9}
};
for (int i = 0; i < 3; i++)
{
for (auto j : students[i]) //用上c++11的新方法,挺好的
{
cout << j << " ";
}
cout << endl;
}
三维数组也是类似,这里给出代码:
int students[2][2][2]
{
{
{1,2},
{3,4},
},
{
{5,6},
{7,8},
}
};
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
for (auto k : students[i][j])
{
cout << k << " ";
}
cout << endl;
}
cout << endl;
}
结果:
数组使用注意:
-
除非逼不得已要用数组,否则一律不用;因为越界漏洞这个是个老生常谈的问题,极可能程序产生不可预知的错误或者被攻击!
-
多维数组在操作系统内存大多数是按照低维度优先排序
array之重温
常用操作
- size()用于查询容器大小
- fill(const int)用于全部初始化
- at(num) 用于安全访问(越界会抛出异常)
- 重载 [ ],类似于数组访问,会越界
- 重载 == 可用于两个比较
以上是最基本用法!
示范代码:
std::array<int, 3> StusID{};
std::array<int, 3> _StusID{25,25,25};
cout << "size = " << StusID.size() << endl;
StusID.fill(25);
for (int i = 0; i < StusID.size(); i++)
{
//cout << "stu[" << i << "] = " << StusID[i] << endl; //不安全
cout << "stu[" << i << "] = " << StusID.at(i) << endl;
}
if (StusID == _StusID)cout << "相等" << endl;
else cout << "不相等" << endl;
结果:
vector之重温
常用操作
1、初始化操作
有五种方式,以下可见:
std::vector<int> StuID1; //空容器
std::vector<int> StuID2{ 3,4,5 }; //有三个数
std::vector<int> StuID3(5); //有五个数,并全为0
std::vector<int> StuID4(3,50); //3个数,全为50
访问结果显示:
2、常用方法
- push_back(value) 向容器插入一个数
- assign(num,value) 重新初始化容器为num个value值
- clear() 清空容器
- empty() 容器为空返回1,否则返回0
- at(num) 安全访问容器内容(越界抛异常)
示例代码:
std::vector<int> StuID1; //定义空容器
StuID1.push_back(5); //插入一个5
StuID1.push_back(10); //插入一个10
for (int i = 0; i < StuID1.size(); i++) //遍历
{
cout << "Stu1 [" << i << "] = " << StuID1.at(i) << " ";
}
cout << endl;
StuID1.assign(3, 8); //重新初始化
for (int i = 0; i < StuID1.size(); i++)
{
cout << "Stu1 [" << i << "] = " << StuID1.at(i) << " ";
}
cout << endl;
StuID1.clear(); //清空
if (StuID1.empty())cout << "空的" << endl;
else cout << "不是空的" << endl;
结果:
感谢自己努力拼搏!!!