gpt4 book ai didi

c++ - array<> 不能简单地在内部交换指针

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:55:04 25 4
gpt4 key购买 nike

对于用TR1引入STL的容器数组<>,我有下面的问题。

在“The C++ standard library A Tutorial and Reference”一书的第 263 页中:

Note, however, that an array<> can’t simply swap pointers internally. For this reason, swap() has linear complexity and the effect that iterators and references don’t swap containers with their elements.

我想知道为什么 array<> 不能考虑交换指针的恒定开销?

最佳答案

您可能会误入“C[++] 数组只是指针”的谬论。 不,它们不是。在某些情况下(主要是函数调用),数组退化为指针。更正式地说,存在从数组到指向其第一个成员的指针的隐式转换。

但它们是完全不同的东西。指针是一个地址——通常为 4 或 8 个字节,具体取决于硬件。数组是一个接一个的对象序列。 sizeof 可以区分:

int main()
{
int arr[5];
int *p = arr; // decay/implicit conversion happening here
std::cout << sizeof arr << ':' << sizeof p;
}

这将在典型的 32 位 PC 上输出 20:4

如您所见,交换指针很快,但交换实际数组则不然——您确实必须交换单个元素,因此这需要的时间与元素数量呈线性关系。 请注意 std::array 确实是数组的包装器。


不幸的是,C 和 C++ 语法决定使困惑变得更糟——在函数参数类型上,可以使用数组语法,但“衰减”是在类型本身上执行的。这意味着它的功能是这样的:

void foo(int a[]);
void bar(char b[40]);

实际上并不接受数组,他们接受指针。这些函数声明完全相同如下:

void foo(int *a);
void bar(char *b);

如此之多,以至于您实际上可以将一个用作另一个的前向声明:

#include <iostream>

void foo(int a[40]);

int main()
{
int x = 42;
foo(&x);
}

void foo(int *a)
{
std::cout << a[0] << std::endl;
}

Live example

关于c++ - array<> 不能简单地在内部交换指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25442533/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com