C++
定长数组
数组是一种基本的数据结构,用于按顺序存储元素的集合。但是元素可以随机存取,因为数组中的每个元素都可以通过数组索引来识别。
数组可以有一个或多个维度。
#include <iostream>
#include<algorithm>
using namespace std;
int main() {
// 【1】初始化
int a0[5];
int a1[5] = {1, 2, 3}; // 其他元素将被设置为默认值
// 【2】获取数组长度
int size = sizeof(a1) / sizeof(*a1);
cout << "The size of a1 is: " << size << endl;
// 【3】访问元素
cout << "The first element is: " << a1[0] << endl;
// 【4】迭代所有元素
cout << "[Version 1] The contents of a1 are:";
for (int i = 0; i < size; ++i) {
cout << " " << a1[i];
}
cout << endl;
cout << "[Version 2] The contents of a1 are:";
for (int& item: a1) {
cout << " " << item;
}
cout << endl;
// 【5】修改元素
a1[0] = 4;
// 【6】排序
sort(a1, a1 + size);
}
动态数组
数组具有固定的容量,我们需要在初始化时指定数组的大小。有时它会非常不方便并可能造成浪费。
因此,大多数编程语言都提供内置的动态数组,它仍然是一个随机存取的列表数据结构,但大小是可变的。
#include <iostream>
#include<vector>
int main() {
// 【1】初始化
vector<int> v0;
vector<int> v1(5, 0);
// 【2】 创建副本
vector<int> v2(v1.begin(), v1.end());
vector<int> v3(v2);
// 【3】把定长数组转为动态数组
int a[5] = {0, 1, 2, 3, 4};
vector<int> v4(a, *(&a + 1));
// 【4】获取数组长度
cout << "The size of v4 is: " << v4.size() << endl;
// 【5】修改/添加/删除/清空元素
v4[0]=1;
v4.push_back(15);
v4.pop_back();
v4.clear();
// 【6】迭代vector
cout << "[Version 1] The contents of v4 are:";
for (int i = 0; i < v4.size(); ++i) {
cout << " " << v4[i];
}
Python
很多编程语言中都有数组这一对象,Python和它对应的则是列表list,还有元组tuple。元组和列表有很多相似地方,最大区别在于不可变。可以理解为Python中的list对应为其它与语言中的可变数组,而tuple对应为不可变数组。不可变指的是不能对里面的元素进行增加、删除、修改、排序、倒序等操作。
List
if __name__ == '__main__':
# 【1】初始化
a = []
b = [1, 'hello', [1], False]
list_c = list('hello')
# 【2】获取数组长度
print("list c的长度为:%d" % len(list_c))
# 【3】访问元素
d = list_c[-2]
e = list_c[1:2]
f = list_c[:]
# 【4】迭代所有元素
print("[Version 1] The contents of a1 are:")
for c in list_c:
print(c)
print("[Version 2] The contents of a1 are:")
for i, c in enumerate(list_c):
print('第%d个元素是%c' % (i, c))
# 【5】修改/添加元素
list_c[0] = '1'
list_c.append('Runoob')
list_c.insert(0, '1')
list_c.extend(b)
# 【6】删除/清空元素
del list_c[2]
list_c.pop()
list_c.remove('1')
list_c = []
# 【7】查询某个值的索引、查询某个值出现次数
print(list_c.index('1'))
print(list.count('g'))
# 【8】组合列表
list_d = [1, 2, 3] + [4, 5, 6]
# 【9】重复列表
list_e = [1, 2, 3] * 4
# 【10】判断元素是否在列表中
print(5 in list_e)
# 【11】排序
list_c.sort(reverse=True)
# 【12】逆序
list_c.reverse()
Tuple
C#
Array
int[] arr;
int[] arr = {1,2,3,4};
int[] arr = new int[1000];
List
//【1】初始化
int[] list = { 34, 72, 13, 44, 25, 30, 10 };
// 逆转数组
Array.Reverse(list);
javascript
Array
//【1】初始化
var arr1=new Array();
var arr2=new Array("Saab","Volvo","BMW");
var arr3=["Saab","Volvo","BMW"];