c++ 学习之路(四)数组
数组初始化
- 可以先定义容量然后在赋值。
#include <iostream>
using namespace std;
int main() {
// define a list
int a[2];
a[1] = 1;
a[0] = 2;
for(int i =0; i<2; i++) {
// 2 1
cout << a[i] << '\t';
}
return 0;
}
这里,我们先定义了一个数组,然后挨个将值赋在数组中。
另外可以直接给数组赋值,如:
#include <iostream>
using namespace std;
int main() {
int a[] = {1,2,3,4,5};
int b[5] = {1,2,3,4,5};
for(int i = 0; i<5; i++){
// 1 2 3 4 5
cout << a[i] << '\t';
}
cout << '\n';
for(int i =0; i<5; i++) {
// 1 2 3 4 5
cout << b[i] << '\t';
}
return 0;
}
这就是几种赋值方法。
二维数组也一样
#include <iostream>
using namespace std;
int main() {
int a[3][2] = {{1,2},{3,4},{5,6}};
for(int i = 0; i < 3; i++) {
for(int j =0; j<2 ; j++) {
cout << a[i][j] << '\t';
}
}
return 0;
}
数组的插入和删除
数组的插入可以扩大数组的容量,然后将插入后面的数组向后移一个单元。例如:
#include <iostream>
using namespace std;
int main() {
int a[20] = {1,2,3,4,5};
// at element at the third index
for(int i = 4; i >=2; i--) {
a[i+1] = a[i];
}
a[2] = 5;
for(int i =0; i < 6; i++) {
// 1 2 5 3 4 5
cout << a[i] << '\t';
}
return 0;
}
删除元素:
#include <iostream>
using namespace std;
int main() {
int a[20] = {1,2,3,4,5};
// delete element at the third index
for(int i = 2; i < 5; i++) {
a[i] = a[i+1];
}
for(int i =0; i < 4; i++) {
// 1 2 4 5
cout << a[i] << '\t';
}
return 0;
}
指向数组的指针
#include <iostream>
using namespace std;
int main() {
int a[] ={1,2,3,4,5};
int* p = &a[2];
// 3
cout << *p << endl;
int* q = a;
for(int i =0 ;i < 5; i++) {
cout << a[i] << '\t';
}
return 0;
}
今天的内容就到这里了。下次见啦 ^ _ ^