In Java I can do
List<String> data = new ArrayList<String>(); data.add("my name");
How would I do the same in C++?
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.
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.
An ArrayList does not check for duplicates, you could stuff the same object in there over and over again.
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):
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With