在Java中我可以做
List<String> data = new ArrayList<String>();
data.add("my name");
我如何在 C++ 中做同样的事情?
Use std::vector
and std::string
:
#include <vector> //for std::vector
#include <string> //for std::string
std::vector<std::string> data;
data.push_back("my name");
请注意,在 C++ 中,您不需要使用new
每次创建一个对象时。物体data
通过调用默认构造函数进行默认初始化std::vector
。所以上面的代码没问题。
在 C++ 中,摩托是:Avoid new
越多越好.
如果您在编译时已经知道大小并且数组不需要增长,那么您可以使用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
阅读文档了解更多详细信息:
- std::向量 http://en.cppreference.com/w/cpp/container/vector
- 标准::字符串 http://en.cppreference.com/w/cpp/container/string
- 标准::数组 http://en.cppreference.com/w/cpp/container/array
C++ 标准库有许多容器。根据具体情况,您必须选择最适合您目的的一种。我不可能逐一谈论它们。但这里的图表很有帮助(source http://linuxsoftware.co.nz/cppcontainers.html):
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)