I wanted to know how you could create an array of objects with the vector class.
You already have it:
std::vector<Objeto> elementos;
And call the constructor method of each object.
You already do it.
You have 3 ways to add items to your std::vector
, according to the class documentation, your builder has 8 signatures, of which the default constructor is relevant (for you):
std::vector();
All it does is create an empty vector, it's the constructor you're calling in your main
:
int main(){
vector<Objeto> elementos;
return 0;
}
Once the vector is created, to add elements you have as options:
- Copy inside the vector an element created outside the vector.
- Move inside the vector an element created outside the vector.
- Construct elements within the vector.
Copy.
It's the simplest way, you create the object you want to insert into the vector and then the insert at the end of the vector :
std::vector<Objeto> elementos;
Objeto o;
elementos.push_back(o);
You could also insert it in a specific position :
std::vector<Objeto> elementos;
Objeto o;
elementos.insert(elementos.begin(), o); // Copiamos 'o' al principio
Move.
If the object to be inserted was a temporary value, it would be moved to the interior of the vector:
std::vector<Objeto> elementos;
elementos.push_back(Objeto{}); // El objeto creado es temporal
elementos.push_back({}); // Podríamos obviar el nombre del tipo, pues ya es conocido.
It also works with temporary objects:
std :: vector elements;
elementos.insert(elementos.end(), Objeto{}); // El objeto es movido al final
elementos.insert(elementos.begin(), {}); // El objeto es movido al inicio
Build.
You can let the vector construct the objects internally where they belong:
std::vector<Objeto> elementos;
elementos.emplace(elementos.end()); // El vector crea el objeto directamente en el final
If your Objeto
would not have had a default constructor, you could have passed the parameters of the constructor to the function std::vector::emplace
:
struct Objeto {
Objeto(int){};
};
std::vector<Objeto> elementos;
// El vector crea el objeto directamente en el final con el valor '1'
// como parámetro del constructor.
elementos.emplace(elementos.end(), 1);
If we always want to build elements at the end of the vector, we have an alternative for it :
struct Objeto {
Objeto(int){};
};
std::vector<Objeto> elementos;
// El vector crea el objeto directamente en el final con el valor '1'
// como parámetro del constructor.
elementos.emplace_back(1);
Where is the constructor called?
In the case of Copy the constructor is called where you create the original object, inserting the element in the vector calls the copy constructor.
In the case of Move the constructor is called in the place where the original object is created, when the element is inserted, the movement constructor is called.
In the case of Construct within the constructor calls it internally the vector, no more constructors are involved in the process.