How to put classes inside vector and manipulate variables with push_back?

Asked

Viewed 275 times

1

It’s definitely something simple, but I researched and didn’t understand how to do.

If I have for example the following class, with two variables:

class x {
public:
    int var1, var2;
};

I want to create a vector of this class, then I declare:

vector<x> teste;

With array, it would be easy. But, forgetting the use of setters, just to facilitate here, I want to assign values to the two variables and then do a push_back vector.

How I do?

1 answer

1


The most direct without changing anything would be:

std::vector<x> teste;

x obj1; //criar o objeto
obj1.var1 = 10;
obj1.var2 = 20;
teste.push_back(obj1); //adicionar ao vetor com push_back

std::cout << teste[0].var1 << " " << teste[0].var2; //10 20

See this example in Ideone

But if you use a constructor it is much more practical. You need to include it in your class first:

class x {
public:
    int var1, var2;
    x(int v1, int v2):var1(v1), var2(v2) {} //construtor com inicializadores
};

Then the creation of the object is:

x obj1(10,20); //agora cria utilizando o construtor
teste.push_back(obj1); //adicionar ao vetor com push_back

See also this example in ideone

If you want you can do it all in one call that would be the most practical, so:

teste.push_back(x(10,20));

This way you can make several additions without having to constantly declare auxiliary variables.

As the friend @Marioferoldi commented, you can also use the method emplace_back as an alternative to push_back with the difference that builds the element and adds, so it does both at the same time. The construction is made based on the type of the vector.

teste.emplace_back(10, 20); //constroi o x com 10 e 20, e adiciona ao vector

Browser other questions tagged

You are not signed in. Login or sign up in order to post.