什么是性病::阵列和std :: vector的区别?当你使用一个比其他? [英] What is the difference between std::array and std::vector? When do you use one over other?

查看:127
本文介绍了什么是性病::阵列和std :: vector的区别?当你使用一个比其他?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是数组 STD之间的区别:的std ::矢量?当你使用一个比其他?

What is the difference between std::array and std::vector? When do you use one over other?

我一直使用并认为 STD:向量作为C ++使用C数组的方式,所以有什么区别

I have always used and considered std:vector as an C++ way of using C arrays, so what is the difference?

推荐答案

的std ::阵列仅仅是个经典的C数组的类版本。这意味着,它的大小是固定在编译时,它会(例如取叠层上的空间)被分配为单个块。它具有的优点是表现略好,因为有在物体和排列数据之间没有间接

std::array is just a class version of the classic C array. That means its size is fixed at compile time and it will be allocated as a single chunk (e.g. taking space on the stack). The advantage it has is slightly better performance because there is no indirection between the object and the arrayed data.

的std ::矢量是包含指针到堆一个小班。 (所以当你分配一个的std ::矢量,它总是调用)。他们是稍微慢一些访问,因为这些指针必须追逐才能到阵列的数据...但是换来的,他们可以调整大小,他们只需要堆栈空间微不足道的金额,不管他们是多么的大。

std::vector is a small class containing pointers into the heap. (So when you allocate a std::vector, it always calls new.) They are slightly slower to access because those pointers have to be chased to get to the arrayed data... But in exchange for that, they can be resized and they only take a trivial amount of stack space no matter how large they are.

至于何时使用一个比其他,老老实实的std ::矢量几乎总是你想要什么。在栈上创建大对象通常是令人难以接受,而间接的额外的水平通常是不相关的。 (例如,如果通过所有元素的重复,额外的内存访问仅在循环的开始发生一次。)

As for when to use one over the other, honestly std::vector is almost always what you want. Creating large objects on the stack is generally frowned upon, and the extra level of indirection is usually irrelevant. (For example, if you iterate through all of the elements, the extra memory access only happens once at the start of the loop.)

Vector的元素都保证是连续的,所以你可以通过&放大器; VEC [0] 到任何函数期待一个指向数组的指针;例如,C库函数。 (顺便说一句,的std ::矢量<字符> BUF(8192); 是分配呼叫本地缓冲区一个伟大的方式读/写或不直接调用类似

The vector's elements are guaranteed to be contiguous, so you can pass &vec[0] to any function expecting a pointer to an array; e.g., C library routines. (As an aside, std::vector<char> buf(8192); is a great way to allocate a local buffer for calls to read/write or similar without directly invoking new.)

这表示,由于缺乏间接额外的水平,加上编译时间常数的大小,可以使的std ::阵列显著为快一个非常小的数组获得创建/销毁/访问了不少。

That said, the lack of that extra level of indirection, plus the compile-time constant size, can make std::array significantly faster for a very small array that gets created/destroyed/accessed a lot.

所以,我的建议是:使用的std ::矢量除非(a)您分析器告诉你,你有问题的的(B )数组是微小的。

So my advice would be: Use std::vector unless (a) your profiler tells you that you have a problem and (b) the array is tiny.

这篇关于什么是性病::阵列和std :: vector的区别?当你使用一个比其他?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆