c++ primer学习笔记(7)-数组
2011-02-24 21:08 Clingingboy 阅读(196) 评论(0) 编辑 收藏 举报
1.数组的定义
// both buf_size and max_files are const
const unsigned buf_size = 512, max_files = 20;
int staff_size = 27; // nonconst
const unsigned sz = get_size(); // const value not known until run time
char input_buffer[buf_size]; // ok: const variable
string fileTable[max_files + 1]; // ok: constant expression
double salaries[staff_size]; // error: non const variable
int test_scores[get_size()]; // error: non const expression
int vals[sz]; // error: size not known until run time
注意点:
- 数组的维数必须是const的,对于这一点很诧异,第二条语句居然不通过,而第5条则可以,不知道编译器是怎么搞的
- 维数声明在变量后面,c#则在前面
2.显示初始化({})
const unsigned array_size = 3;
int ia[array_size] = {0, 1, 2};
3.特殊的字符数组
由于字符串非常常用,所以特殊一些
char ca1[] = {'C', '+', '+'}; // no null
char ca2[] = {'C', '+', '+', '\0'}; // explicit null
char ca3[] = "C++"; // null terminator added automatically
注意:
- ca2和ca3是相同的,维数为4(注意数组不要超界) const char ch3[6] = "Daniel"; // error: Daniel is 7 elements
- 数组不可直接复制和赋值的
int ia[] = {0, 1, 2}; // ok: array of ints
int ia2[](ia); // error: cannot initialize one array with another
int main()
{
const unsigned array_size = 3;
int ia3[array_size]; // ok: but elements are uninitialized!
ia3 = ia; // error: cannot assign one array to another
return 0;
}
4.数组下标访问
可用size_t来访问数组元素,而非数值
const size_t array_size = 10;
int ia[array_size]; // 10 ints, elements are uninitialized
// loop through array, assigning value of its index to each element
for (size_t ix = 0; ix != array_size; ++ix)
ia[ix] = ix;
数组是很多数据结构的基础,长度不可变,较为底层,可用c++标准库中的一些高级数据结构来简化数组的操作
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现