24

In Java I can do

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

How would I do the same in C++?

learner
  • 11,490
  • 26
  • 97
  • 169
  • 13
    People, stop downvoting. It discourages programmers coming from other languages to learn C++. There is nothing wrong in the question. – Nawaz Jan 20 '13 at 17:09
  • 3
    I wonder what thought process, if any, went into that downvote. – kasavbere Jan 20 '13 at 17:10

2 Answers2

56

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 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 <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:


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):

enter image description here

Nawaz
  • 353,942
  • 115
  • 666
  • 851
0

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

blackmath
  • 242
  • 1
  • 10