C++ Premier之3.5:数组
相比vector,数组大小固定,损失了一定的灵活性,但是性能稳定。
初始化
初始化数组时,维度必须是一个常量
constexpr unsigned sz = 42;
int arr[10];
int* parr[sz];
string bad[cnt];//错误
string good[sz];
string strs[get_size()];//错误
//显式初始化
const unsigned sz = 3;
int ia1[sz] = { 1,2,3 };
int a2[] = { 2,3,4 };
int a3[53] = { 3,4,5 };
string a4[4] = {"hello","olleh"}//未定义部分自动补0,补“”
//可以使用字符串字面值进行初始化,但不可以拷贝和赋值
char a3[] = "c++";
int a2[] = a3;//非法
访问数组元素
1、使用 数组记录考试成绩段
int main() {
unsigned scores[5] = {};//分为5段
unsigned grade;
while (cin >> grade) {//ctrl+z+回车,输入结束
scores[grade / 25] = scores[grade / 25] + 1;
}
//使用sizeof获取数组的长度
for (int i = 0; i < sizeof(scores) / sizeof(scores[0]);i++) {
cout << scores[i] <<" ";
}
cout << "sizeof(scores)" << sizeof(scores) << ";" << sizeof(scores[0]) << endl;
return 0;
}
运行结果:
指针和数组
利用数组名的指针特性输出数组arr的全部元素
int a[] = {0,1,2,3,4,5,6,7,8,9}
int *e = a[10]
for(int *b = arr;b!=e;++b)
cout<<*b<<endl;
begin、end与数组
int a[] = {0,1,2,3,4,5,6,7,8,9};
int* pbeg = begin(arr),;pend = end(arr);
while(pbeg != pend && >=0)
++pbeg;
练习
3.34 数组元素置零
int main() {
int a[5] = { 1,2,2,3,4 };
int* pa = a;
for (int i = 0; i < 5; ++i) {
*(pa + i) = 0;
cout << a[i] << endl;
}
return 0;
}
3.35比较数组是否相等
#include <iostream>
#include <vector>
#include <iterator>
using namespace std;
bool compare(int* const pb1, int* const pe1, int* const pb2, int* const pe2) {
for (int* i = pb1, *j = pb2; (i != pe1) && (j != pe2); ++i, ++j)
if (*i != *j) return false;
}
int main()
{
int arr1[3] = { 0, 1, 2 };
int arr2[3] = { 0, 2, 4 };
if (compare(begin(arr1), end(arr1), begin(arr2), end(arr2)))
cout << "The two arrays are equal." << endl;
else
cout << "The two arrays are not equal." << endl;
cout << "==========" << endl;
vector<int> vec1 = { 0, 1, 2 };
vector<int> vec2 = { 0, 1, 2 };
if (vec1 == vec2)
cout << "The two vectors are equal." << endl;
else
cout << "The two vectors are not equal." << endl;
return 0;
}