Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java ArrayList in C++ [duplicate]

Tags:

In Java I can do

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

How would I do the same in C++?

like image 800
learner Avatar asked Jan 20 '13 16:01

learner


People also ask

Does ArrayList in Java allow duplicates?

ArrayList allows duplicate values while HashSet doesn't allow duplicates values. Ordering : ArrayList maintains the order of the object in which they are inserted while HashSet is an unordered collection and doesn't maintain any order.

How do you find duplicates in ArrayList?

One of the most common ways to find duplicates is by using the brute force method, which compares each element of the array to every other element. This solution has the time complexity of O(n^2) and only exists for academic purposes.

Can ArrayList store duplicates?

An ArrayList does not check for duplicates, you could stuff the same object in there over and over again.


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

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

enter image description here

like image 162
Nawaz Avatar answered Oct 06 '22 23:10

Nawaz