数组是内存中的一个位置,以及它后面的一系列串行位置。
考虑我是否有数组 int[] a = [1,2,3,4,5,6,7,8,9,10];
如果我们查看内存中的这个数组,它可能看起来像这样 --
15 null 00000000
null 00000000
null 00000000
a[10] 00001011
a[9] 00001010
10 a[8] 00001001
a[7] 00001000
a[6] 00000111
a[5] 00000110
a[4] 00000101
5 a[3] 00000100
a[2] 00000011
a[1] 00000010
a[0] 00000001
other stuff 00011101
0 other stuff 01010101
您可以在数组中随机访问,因为编译器正在为您找到您正在寻找的确切地址。
例如在这种情况下,如果我运行该函数
print(a*); //print the location in memory of a (the pointer to a)
它会输出
2
现在当我要求 [2]
print (a[2])
编译器实际上在做的是这个
print (&(a*+2) // print the values at the memory location
// that is 2 plus the pointer to a
这意味着它应该打印出内存位置4的值,即
3
当我们说一个数组可以随机访问时,这意味着访问的时间是恒定的,因为找到元素 a[100000] 和 a[1] 都需要相同的时间。
1.) look-up a.
2.) add the index to a.
3.) look-up the value at a + index.
现在向量只是一个数组的包装器。它添加了特殊功能并为数组定义“行为”。想象它像一个包含 3-4 条数据的结构,其中一些数据是指向特殊“向量函数”的指针。
想象一下这样的数据。
struct vect {
int* array;
int arraysize;
int* functionPtr1;
int* functionPtr2;
int* functi....
};
我要避免在 c 中看起来如何的 gorp,因为我不是很好并且肯定会出错,但是在像 java 这样的面向对象语言中,我们的向量看起来像这样
vect.array[1];
int arg2 = vect.array[2];
vect.functionPtr1(2);
int vectSize = vect.arraysize;
很简单。令人困惑的是,c++ 允许您在对象上定义 [] 运算符。当您执行此操作时,在 c++ 中的向量中。
vect[2];
它实际上只是这里 java 等价物的语法糖:
vect.array[2];
但是 tl;dr;这一切的版本是向量只是一个用于将函数包装在原始数组周围的对象。 C++ 提供了特殊的语法糖,因此您可以直接从对象指针寻址原始数组,而不仅仅是从对象数组成员,但是获取对象数组成员的工作仍在完成,只是抽象出来。