Search code examples
c++classobjectvectorpush-back

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;
}

Solution

  • 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);