将一个到多个相同类型的对象串联到一起,所组成的类型
int a ; int b[10];
区分类型,b
的类型为int[10]
int a[3] = {1,2}; //第三个元素为0
int b[] = {1,2,3} //int[3]
不能使用auto
声明数组类型
数组不支持复制
数组的长度必须为一个常量表达式
字符串的数组特殊性 (在字符串结尾隐式加上\0
表示结束)
char str[] = "Hello"; //char[6]
char srt[] = {'H','e','l','l','o'}; //char[5]
指针数组与数组的指针
int x1,x2,x3; //指针数组
int* a[3] = {&x1, &x2, &x3}; //a类型为int*[3]
int a[3] = {1, 2, 3}; //数组的指针
int (*b)[3] = &a; //b类型为int(*)[3]
声明数组的引用
int a[3] = {1, 2, 3};
int (&b)[3] = a;
(左值:能够放在等号左侧的值(C),C++中 locater-value)
x[y]; // 会被解析成*(x+y)
通常会产生转换
隐式转换会丢失一部分信息
int a[3] = {1,2,3}; //a int[3]
auto b = a; //b int*
可以通过声明引用来避免隐式转换
int a[3] = {1,2,3}; //a int[3]
auto b = a; //b int*
auto& c = a; //c int(&)[3]
不能使用extern
指针来声明数组
int a[3] = {1, 2, 3};
a;
&(a[0]); //开头指针
std::begin(a); // int*
std::cbegin(a); // const int*
a+3;
&(a[3]); //结尾指针
std::end(a);
std::cend(a); //end和cend指向数组最后一个元素的下一个元素
求元素个数
sizeof
对象的字节数(C语言常用)sizeof(a)/sizeof(int)
std::size(a);
(推荐方法)
std::cend(a) - std::cbegin(a);
运行期操作 (编译器可以解决,不推荐)
数组的遍历
int a[3] = {1,2,3};
size_t index = 0;
while(index < std::size(a)){
index = index + 1;
}
int a[3] = {1,2,3};
auto ptr = std::cbegin(a);
while(ptr != std::cend(a)){
ptr = ptr + 1;
}
for(int x:a){
//语法塘 c++insight可以查看 简化书写 C++11开始
}
字符串本质上也是数组
char str[] = "Hello"; //char[6] null-terminated string
auto ptr = str; //char*
隐式转化为指针类型,对字符串进行操作时寻找'\0'
代表字符串结束
返回字符串长度
#include <cstring>
strlen(a);
本质:数组的数组
int a[3][4];
聚合初始化
int a[][4] = {{1,2,3},{4,5,6,7}};
多维数组的索引和遍历
int x[3][4] = {1,2,3,4,5};
for(auto& p:x){
for(auto q:p){
std::cout<< q <<'\0';
}
}
指针与多维数组
C++标准库中定义的类模板
std::vector<int> x;
与内建数组相比,更侧重于易用性(性能差于内建数组)
std::vector<int> a = {1,2,3};
std::vector<int> a(3);
其他方法
获取元素个数,判断是否为空
std::vector<int> a = {1,2,3};
a.size(); //输出元素个数
a.empty(); //输出是否为空
插入、删除元素
a.push_back(2); //结尾插入一个元素2
a.pop_back(); //从结尾删除一个元素
vector的比较
[]
v.s.at
at在索引超出时会报错,更加安全
begin/end
函数 v.s. begin/end
方法
auto x = a.begin();
auto y = a.end(); //返回一个iterator
(*x)
y[1]
添加元素可能使迭代器失效
多维vector
std::vector<std::vector<int>> x;
x.push_back(std::vector<int>());
x[0].push_back(1);
std::cout<<x[0][0]<<std::endl;
std::vector<std::vector<int>> y = {{1,2,3},{4,5}};
从.
到->
std::vector<int> x;
std::vector<int>* ptr = &x;
(*ptr).size();
ptr->size(); //语法塘 同上一行相同
C++标准库中定义的类模板,用于内建字符串的代替品
std::string
是std::basic_string<char>
的别名
与内建字符串相比,更侧重于易用性
构造与初始化
#include <string>
std::string str = "Hello";
str = str + "!";
std::string str2 = "World";
std::string str3;
str3 = str + str2;
其他方法
str[2]
因篇幅问题不能全部显示,请点此查看更多更全内容