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

1

It sure is something simple, but I researched and did not 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, so I declare:

vector<x> teste;

With array, it would be easy. But, forgetting the use of setters , for ease here, I want to assign values to the two variables and then make a push_back % vector.

How do I do it?

    
asked by anonymous 29.05.2018 / 01:54

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 builder it gets much more practical. First you need to include it in your class:

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

After 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 on ideone

If you want you can do everything in one call that would be the most practical, like this:

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

So you can do various additions without having to constantly declare auxiliary variables.

As your friend @MarioFeroldi commented, you can also use the emplace_back method instead to push_back with the difference that constructs the element and adds, so it does both at the same time. The construction is done based on the type of the vector.

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