C ++中的Java ArrayList [英] Java ArrayList in C++
问题描述
在Java中我可以做到
In Java I can do
List<String> data = new ArrayList<String>();
data.add("my name");
我如何在C ++中做同样的事情?
How would I do the same in C++?
推荐答案
使用 std :: vector
和 std :: string
:
#include <vector> //for std::vector
#include <string> //for std::string
std::vector<std::string> data;
data.push_back("my name");
请注意,在C ++中,您不需要使用 new
每次创建一个对象。通过调用 std :: vector
的默认构造函数来默认初始化对象 data
。所以上面的代码很好。
Note that in C++, you don't need to use new
everytime you create an object. The object data
is default initialized by calling the default constructor of std::vector
. So the above code is fine.
在C ++中,moto是:尽可能避免新
。
In C++, the moto is : Avoid new
as much as possible.
如果你已经知道编译时的大小并且数组不需要增长,那么你可以使用 std :: array
:
If you know the size already at compile time and the array doesn't need to grow, then you can use std::array
:
#include <array> //for std::array
std::array<std::string, N> data; //N is compile-time constant
data[i] = "my name"; //for i >=0 and i < N
阅读文档了解更多详情:
Read the documentation for more details:
- std::vector
- std::string
- std::array
C ++标准库有许多容器。根据情况,您必须选择最适合您的目的。我不可能谈论它们中的每一个。但这里的图表有很多帮助(来源):
C++ Standard library has many containers. Depending on situation you have to choose one which best suits your purpose. It is not possible for me to talk about each of them. But here is the chart that helps a lot (source):
这篇关于C ++中的Java ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!