std::array 和 std::vector 有什么区别?你什么时候用一个? [英] What is the difference between std::array and std::vector? When do you use one over other?

查看:141
本文介绍了std::array 和 std::vector 有什么区别?你什么时候用一个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

std::arraystd::vector 有什么区别?你什么时候用一个?

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

我一直使用并考虑将 std:vector 作为使用 C 数组的 C++ 方式,那么有什么区别?

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

推荐答案

std::array 只是经典 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::vector 是一个包含指向堆的指针的小类.(因此,当您分配 std::vector 时,它总是调用 new.)它们的访问速度稍慢,因为必须追逐这些指针才能访问数组数据... 但作为交换,它们可以调整大小,而且无论它们有多大,它们只占用很少的堆栈空间.

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::vector 几乎总是你想要的.在堆栈上创建大对象通常是不受欢迎的,额外的间接级别通常是无关紧要的.(例如,如果您遍历所有元素,则额外的内存访问只会在循环开始时发生一次.)

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.)

向量的元素保证是连续的,因此您可以将 &vec[0] 传递给任何需要指向数组的指针的函数;例如,C 库例程.(顺便说一句,std::vector buf(8192); 是一种很好的方法来为 read/write 或类似的调用分配本地缓冲区,而无需直接调用 new.)

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::array 显着更快很多.

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::vector 除非(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::array 和 std::vector 有什么区别?你什么时候用一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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