Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pushing back an object in a vector without the object

I know that the correct way of push back an object in a vector is to declare an object of the same class and pass it by value as argument of method push_back. i.e. something like

class MyClass{
    int a;
    int b;
    int c;
};

int main(){
    std::vector<MyClass> myvector;

    MyClass myobject;
    myobject.a = 1;
    myobject.b = 2;
    myobject.c = 3;

    myvector.push_back(myobject);
    return 0;
}

My question is: it's possible to push back an object passing only the values of the object and not another object? i.e. something like

class MyClass{
    int a;
    int b;
    int c;
};

int main(){
    std::vector<MyClass> myvector;

    int a = 1;
    int b = 2;
    int c = 3;

    myvector.push_back({a, b, c});
    return 0;
}
like image 475
gvgramazio Avatar asked Sep 15 '25 15:09

gvgramazio


1 Answers

If you declare a, b, c as public,

class MyClass{
public:
    int a;
    int b;
    int c;
};

then you could use list initialization:

myvector.push_back({a, b, c});

But it could be better to make a constructor

MyClass::MyClass(int a, int b, int c):
    a(a), b(b), c(c)
{}

and then use vector::emplace_back

myvector.emplace_back(a, b, c);
like image 186
AlexD Avatar answered Sep 17 '25 06:09

AlexD