为什么普通 C 数组索引是有符号的,而 stl 索引是无符号的?

Twi*_*ard 1 c c++ indexing stl

我理解为什么 stl 索引是无符号的,因为你永远不会有负索引。但对于普通的 C 数组,索引有符号的。为什么是这样?

如果有充分的理由对 C 数组索引进行签名,那么为什么他们决定使 stl 索引不同呢?

dbu*_*ush 9

C 中的数组索引实际上只是一个指针偏移量。 x[y]与 完全相同*(x + y)。这允许你做这样的事情:

int a[3] = { 1, 2, 3 };
int *p = a;                   /* p points to a[0]  */
printf("p[1]=%d\n", p[1]);    /* prints 2          */
p += 2;                       /* p points to a[2]  */
printf("p[-1]=%d\n", p[-1]);  /* prints 2          */
Run Code Online (Sandbox Code Playgroud)

这就是允许负数组索引的原因。