Java ArrayList in C ++

In Java I can do

List<String> data = new ArrayList<String>(); data.add("my name"); 

How would I do the same in C ++?

+23
java c ++
Jan 20 '13 at 16:04
source share
2 answers

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"); 

Note that in C ++ you do not need to use new every time you create an object. The data object is initialized by default by calling the default constructor std::vector . So the above code is ok.

In C ++, moto: Avoid new as much as possible .

If you know the size already at compile time, and the array does not need to grow, 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 more in the documentation:




The C ++ Standard Library contains many containers. Depending on the situation, you should choose the one that best suits your purpose. I can not talk about each of them. But here is a chart that helps a lot ( source ):

enter image description here

+50
Jan 20 '13 at 16:05
source share

All together in one line the vector myVec (1, "hello");

0
Jan 20 '13 at 16:45
source share



All Articles