使用数组代替 std::vector 的优点?
我目前看到很多标记为 C++ 且与处理数组有关的问题。
甚至还有一些问题询问 std::vector 无需任何魔法即可提供的数组的方法/功能。
所以我想知道为什么这么多开发人员在 C++ 中选择数组而不是 std::vector ?
I'm currently seeing a lot of questions which are tagged C++ and are about handling arrays.
There even are questions which ask about methods/features for arrays which a std::vector
would provide without any magic.
So I'm wondering why so much developers are chosing arrays over std::vector
in C++?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
一般来说,我更喜欢使用向量而不是数组来完成重要的工作;然而,数组有一些优点:
In general, I strongly prefer using a vector over an array for non-trivial work; however, there are some advantages of arrays:
因为C++03没有向量文字。使用数组有时可以生成更简洁的代码。
与数组初始化相比:
向量初始化可能看起来有些冗长
Because C++03 has no vector literals. Using arrays can sometime produce more succinct code.
Compared to array initialization:
vector initialization can look somewhat verbose
我会选择 C++0x 中可用的 std::array 而不是普通数组,后者也可以像标准数组一样使用初始化列表进行初始化
https://en.cppreference.com/w/cpp/container/array
I'd go for std::array available in C++0x instead of plain arrays which can also be initialized like standard arrays with an initializer list
https://en.cppreference.com/w/cpp/container/array
我认为这是因为许多 C++ 程序员来自 C,还不了解使用
vector
的优势以及其容器免费提供的所有额外 STL 功能。I think this is because a lot of C++ programmers come from C and don't yet understand the advantages of using
vector
and all the extra STL goodies that come for free with its containers.您对数组有更多的控制权
怎么样:
1)您正在处理巨大的数据集,其中数据必须映射文件,而不是使用
malloc
或new
分配,因为它的大小。在这种情况下,担心如果一开始没有保留足够的地址空间该怎么办可能是没有意义的,尽管我认为您可以取消映射 - 扩展 - 重新映射文件,除非地址碎片或我的第二点禁止。2) 使用无锁多处理的代码。停止线程进行重新分配(或任何其他“STL 好东西”)的性能影响可能是不可接受的,因此使用数组,您有更多的控制权,您可能需要在调整大小之前调用很多函数来暂停其他线程任何事物。
顺便说一句,我通常同时处理 1 和 2。结构数组 + 指针工作得非常好,用 C++ 编译,因为您仍然可以在代码的其他地方使用一些 C++ 功能。我相信如果我足够努力的话我可以想到更多的例子
You have much more control with arrays
How about:
1) you are dealing with colossal data sets where the data has to be mapped files and not allocated with
malloc
ornew
because of its size. Under this scenario worrying about what to do if you didn't reserve enough address space at the beginning may be moot, though I suppose you could unmap - extend - remap the file, unless prohibited by address fragmentation or my second point.2) Code that uses lockless multiprocessing. Performance hits of stopping the threads for re-allocation (or any other "STL goodie") may be unacceptable, hence use arrays, you have got much more control, you may need to call a lot of functions to pause other threads before you resize anything.
BTW, I'm usually dealing with 1 and 2 at the same time. Arrays of structures + pointers work wonderfully, Compiling with C++ because you you can still use some C++ features elsewhere in the code. I'm sure I could think of many more examples if I tried hard enough