Use std::vector
and std::string
:
#include //for std::vector
#include //for std::string
std::vector data;
data.push_back("my name");
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.
In C++, the moto is : Avoid new
as much as possible.
If you know the size already at compile time and the array doesn't need to grow, then you can use std::array
:
#include //for std::array
std::array 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++ 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):