简体   繁体   English

我应该使用向量而不是数组吗?

[英]Should I use vectors instead of arrays?

If I have a fixed number of elements of class MyClass, should I use arrays or vectors?, ie: 如果我有MyClass类的固定数量的元素,我应该使用数组或向量吗?,即:

MyClass* myArray[];

or 要么

std::vector<MyClass*> myVector;

?

Use std::array or raw arrays for a small, static number of elements. std::array或raw数组用于少量静态元素。

If you have a lot of elements (more than say 100kb), you hog the stack and are asking for stack corruption / overflow. 如果你有很多元素(超过100kb),你就会占用堆栈并要求堆栈损坏/溢出。 In that case, or if the number of elements can only be known at runtime, use std::vector . 在这种情况下,或者如果元素的数量只能在运行时知道,请使用std::vector

if you know the number in compile time - use static array . 如果你知道编译时的数字 - 使用静态array

if the number is dynamic (obtained from the user) - vector is much better to save you the hurdle of managing the memory 如果数字是动态的(从用户获得) - vector可以更好地为您节省管理内存的障碍

"Fixed" has two meanings in this context. “固定”在这种情况下有两个含义。 The usual one is set once, never change , such as a value read from input. 通常的设置一次,永不改变 ,例如从输入读取的值。 This value is known at runtime and requires dynamic allocation on the heap. 此值在运行时已知,需要在堆上进行动态分配。 Your options are a C-style array with new or a vector; 您的选项是带有new或vector的C风格数组; it is highly recommended you use a vector. 强烈建议您使用矢量。

#include <vector>
#include <iostream>
int main() {
    int size;
    std::cin >> size;
    int *myArray = new int[size];
    std::vector<int> myVector(size);
}   

"Fixed" can also mean a compile-time constant , meaning it is constant for any run of the program. “Fixed”也可以表示编译时常量 ,这意味着它对于程序的任何运行都是常量。 You can use a C-style array or a C++ array (automatic memory allocation on the stack). 您可以使用C样式数组或C ++数组(堆栈上的自动内存分配)。

#include <array>
int main() {
    const int size = 50;
    int myArray[size];
    std::array<int, size> myArray;
}

These are faster, but your program needs to have access to sufficient stack memory, which is something you can change in your project settings. 这些更快,但您的程序需要访问足够的堆栈内存,这是您可以在项目设置中更改的内容。 See this topic for more info. 有关详细信息,请参阅此主题 If the size of the array is really big, you may want to consider allocating on the Heap anyway (vector). 如果数组的大小非常大,您可能需要考虑在Heap上分配(向量)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM