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
It’s interesting to mention
std::vector::emplace_back
, decreases even more:teste.emplace_back(10, 20)
.– Mário Feroldi