Java 的 ArrayList 的 C++ 版本是什么
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3971049/
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
What's the C++ version of Java's ArrayList
提问by interstar
Just getting back into using C++ and trying to convert a simple Java program I wrote recently.
刚刚重新开始使用 C++ 并尝试转换我最近编写的一个简单的 Java 程序。
What's the preferred equivalent to the Java ArrayList in C++?
什么是 C++ 中 Java ArrayList 的首选等效项?
采纳答案by SLaks
Use the std::vector
classfrom the standard library.
使用标准库中的std::vector
类。
回答by Steve Townsend
A couple of additional points re use of vector
here.
vector
这里重新使用了一些额外的要点。
Unlike ArrayList
and Array
in Java, you don't need to do anything special to treat a vector
as an array - the underlying storage in C++ is guaranteed to be contiguous and efficiently indexable.
与Java 中的ArrayList
和不同Array
,您无需执行任何特殊操作即可将 avector
视为数组 - C++ 中的底层存储保证是连续的且可高效索引的。
Unlike ArrayList
, a vector
can efficiently hold primitive types without encapsulation as a full-fledged object.
与 不同ArrayList
, avector
可以有效地保存原始类型而无需封装为成熟的对象。
When removing items from a vector
, be aware that the items above the removed item have to be moved down to preserve contiguous storage. This can get expensive for large containers.
从 中删除项目时vector
,请注意必须将删除项目上方的项目向下移动以保持连续存储。对于大型容器,这可能会变得昂贵。
Make sure if you store complex objects in the vector
that their copy constructor and assignment operators are efficient. Under the covers, C++ STL uses these during container housekeeping.
确保将复杂对象存储在vector
它们的复制构造函数和赋值运算符是有效的。在幕后,C++ STL 在容器内务管理期间使用这些。
Advice about reserve()
ing storage upfront (ie. at vector construction or initialilzation time) to minimize memory reallocation on later extension carries over from Java to C++.
关于reserve()
预先存储存储的建议(即在向量构建或初始化时间),以最大限度地减少从 Java 到 C++ 的后续扩展中的内存重新分配。