C++ 数组 vs 向量:介绍性的异同
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15079057/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Arrays vs Vectors: Introductory Similarities and Differences
提问by Trancot
What are the differences between an array and a vector in C++? An example of the differences might be included libraries, symbolism, abilities, etc.
C++中的数组和向量有什么区别?差异的一个例子可能包括图书馆、象征主义、能力等。
Array
大批
Arrays contain a specific number of elements of a particular type. So that the compiler can reserve the required amount of space when the program is compiled, you must specify the type and number of elements that the array will contain when it is defined. The compiler must be able to determine this value when the program is compiled. Once an array has been defined, you use the identifier for the array along with an index to access specific elements of the array. [...] arrays are zero-indexed; that is, the first element is at index 0. This indexing scheme is indicative of the close relationship in C++ between pointers and arrays and the rules that the language defines for pointer arithmetic.
— C++ Pocket Reference
数组包含特定数量的特定类型元素。为了让编译器在编译程序时可以保留所需的空间量,您必须指定数组在定义时将包含的元素的类型和数量。编译器必须能够在编译程序时确定该值。一旦定义了数组,就可以使用数组的标识符和索引来访问数组的特定元素。[...] 数组是零索引的;也就是说,第一个元素在索引 0 处。这种索引方案表明 C++ 中指针和数组之间的密切关系以及该语言为指针算术定义的规则。
— C++ 袖珍参考
Vector
向量
A vector is a dynamically-sized sequence of objects that provides array-style
operator[]
random access. The member functionpush_back
copies its arguments via copy constructor, adds that copy as the last item in the vector and increments its size by one.pop_back
does the exact opposite, by removing the last element. Inserting or deleting items from the end of a vector takes amortized constant time, and inserting or deleting from any other location takes linear time. These are the basics of vectors. There is a lot more to them. In most cases, a vector should be your first choice over a C-style array. First of all, they are dynamically sized, which means they can grow as needed. You don't have to do all sorts of research to figure out an optimal static size, as in the case of C arrays; a vector grows as needed, and it can be resized larger or smaller manually if you need to. Second, vectors offer bounds checking with theat
member function (but not withoperator[]
), so that you can do something if you reference a nonexistent index instead of simply watching your program crash or worse, continuing execution with corrupt data.— C++ Cookbook
向量是一个动态大小的对象序列,提供数组样式的
operator[]
随机访问。成员函数push_back
通过复制构造函数复制其参数,将该副本添加为向量中的最后一项,并将其大小增加 1。pop_back
通过删除最后一个元素来做完全相反的事情。从向量的末尾插入或删除项目需要分摊常数时间,而从任何其他位置插入或删除需要线性时间。这些是向量的基础知识。他们还有很多。在大多数情况下,向量应该是 C 风格数组的首选。首先,它们是动态调整大小的,这意味着它们可以根据需要增长。您不必像 C 数组那样进行各种研究来找出最佳静态大小;矢量根据需要增长,如果需要,可以手动调整大小。其次,向量提供了at
成员函数的边界检查(但不是operator[]
),这样当你引用一个不存在的索引时你可以做一些事情,而不是简单地看着你的程序崩溃或更糟,继续执行损坏的数据。— C++ 食谱
回答by Matteo Italia
arrays:
数组:
- are a builtin language construct;
- come almost unmodified from C89;
- provide just a contiguous, indexable sequence of elements; no bells and whistles;
- are of fixed size; you can't resize an array in C++ (unless it's an array of POD and it's allocated with
malloc
); - their size must be a compile-time constant unless they are allocated dynamically;
- they take their storage space depending from the scope where you declare them;
- if dynamically allocated, you must explicitly deallocate them;
- if they are dynamically allocated, you just get a pointer, and you can't determine their size; otherwise, you can use
sizeof
(hence the common idiomsizeof(arr)/sizeof(*arr)
, that however fails silently when used inadvertently on a pointer); - automatically decay to a pointers in most situations; in particular, this happens when passing them to a function, which usually requires passing a separate parameter for their size;
- can't be returned from a function;
- can't be copied/assigned directly;
- dynamical arrays of objects require a default constructor, since all their elements must be constructed first;
- 是一个内置的语言结构;
- 从 C89 几乎未修改;
- 只提供一个连续的、可索引的元素序列;没有花里胡哨;
- 大小固定;你不能在 C++ 中调整数组的大小(除非它是一个 POD 数组并且它被分配了
malloc
); - 它们的大小必须是编译时常量,除非它们是动态分配的;
- 它们占用的存储空间取决于您声明它们的范围;
- 如果是动态分配,则必须显式释放它们;
- 如果它们是动态分配的,您只会得到一个指针,而您无法确定它们的大小;否则,您可以使用
sizeof
(因此是常见的习惯用法sizeof(arr)/sizeof(*arr)
,但是当无意中在指针上使用时会默默地失败); - 在大多数情况下自动衰减为指针;特别是,当将它们传递给函数时会发生这种情况,这通常需要为它们的大小传递一个单独的参数;
- 不能从函数返回;
- 不能直接复制/赋值;
- 对象的动态数组需要一个默认构造函数,因为必须首先构造它们的所有元素;
std::vector
:
std::vector
:
- is a template class;
- is a C++ only construct;
- is implemented as a dynamic array;
- grows and shrinks dynamically;
- automatically manage their memory, which is freed on destruction;
- can be passed to/returned from functions (by value);
- can be copied/assigned (this performs a deep copy of all the stored elements);
- doesn't decay to pointers, but you canexplicitly get a pointer to their data (
&vec[0]
is guaranteed to work as expected); - always brings along with the internal dynamic array its size(how many elements are currently stored) and capacity(how many elements can be storedin the currently allocated block);
- the internal dynamic array is not allocated inside the object itself (which just contains a few "bookkeeping" fields), but is allocated dynamically by the allocator specified in the relevant template parameter; the default one gets the memory from the freestore (the so-called heap), independently from how where the actual object is allocated;
- for this reason, they may be less efficient than "regular" arrays for small, short-lived, local arrays;
- when reallocating, the objects are copied(moved, in C++11);
- does not require a default constructor for the objects being stored;
- is better integrated with the rest of the so-called STL (it provides the
begin()
/end()
methods, the usual STLtypedef
s, ...)
- 是一个模板类;
- 是仅 C++ 的构造;
- 实现为动态数组;
- 动态增长和收缩;
- 自动管理它们的内存,在销毁时释放;
- 可以传递给函数/从函数返回(按值);
- 可以复制/分配(这对所有存储的元素执行深度复制);
- 不会衰减为指针,但您可以明确获取指向其数据的指针(
&vec[0]
保证按预期工作); - 总是与内部动态数组一起带来它的大小(当前存储了多少元素)和容量(当前分配的块中可以存储多少元素);
- 内部动态数组不是在对象本身内部分配的(它只包含一些“簿记”字段),而是由相关模板参数中指定的分配器动态分配;默认的从 freestore(所谓的堆)获取内存,与实际对象的分配方式无关;
- 出于这个原因,对于小型、短期、本地阵列,它们可能比“常规”阵列效率低;
- 重新分配时,对象被复制(移动,在 C++11 中);
- 不需要存储对象的默认构造函数;
- 更好地与所谓的 STL 的其余部分集成(它提供
begin()
/end()
方法,通常的 STLtypedef
s,...)
Also consider the "modern alternative" to arrays - std::array
; I already described in another answerthe difference between std::vector
and std::array
, you may want to have a look at it.
还要考虑数组的“现代替代方案” - std::array
; 我已经在另一个答案中描述了std::vector
和之间的区别std::array
,您可能想看看它。
回答by John K?llén
I'll add that arrays are very low-level constructs in C++ and you should try to stay away from them as much as possible when "learning the ropes" -- even Bjarne Stroustrup recommends this (he's the designer of C++).
我要补充一点,数组是 C++ 中非常低级的构造,在“学习绳索”时,您应该尽量远离它们——甚至 Bjarne Stroustrup 也推荐这样做(他是 C++ 的设计者)。
Vectors come very close to the same performance as arrays, but with a great many conveniences and safety features. You'll probably start using arrays when interfacing with API's that deal with raw arrays, or when building your own collections.
矢量与数组的性能非常接近,但具有许多便利和安全功能。在与处理原始数组的 API 交互时,或者在构建自己的集合时,您可能会开始使用数组。
回答by Nicolas Brown
Those reference pretty much answered your question. Simply put, vectors' lengths are dynamic while arrays have a fixed size. when using an array, you specify its size upon declaration:
这些参考几乎回答了你的问题。简单地说,向量的长度是动态的,而数组的大小是固定的。使用数组时,在声明时指定其大小:
int myArray[100];
myArray[0]=1;
myArray[1]=2;
myArray[2]=3;
for vectors, you just declare it and add elements
对于向量,您只需声明它并添加元素
vector<int> myVector;
myVector.push_back(1);
myVector.push_back(2);
myVector.push_back(3);
...
at times you wont know the number of elements needed so a vector would be ideal for such a situation.
有时您不知道所需元素的数量,因此向量将是这种情况的理想选择。