In Java I can do
List<String> data = new ArrayList<String>();
data.add("my name");
How would I do the same in C++?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Use
std::vectorandstd::string:Note that in C++, you don’t need to use
neweverytime you create an object. The objectdatais default initialized by calling the default constructor ofstd::vector. So the above code is fine.In C++, the moto is : Avoid
newas 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:Read the documentation for more details:
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):