gvgramazio
gvgramazio

Reputation: 1154

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

Upvotes: 4

Views: 1353

Answers (2)

srdjan.veljkovic
srdjan.veljkovic

Reputation: 2548

To make it work you need at least a C++11 compiler and you need to make a constructor:

class MyClass {
    int a;
    int b;
    int c;
public:
    MyClass(int a_, int b_, int c_) : a(a_), b(b_), c(c_) {}
};

You could also make a, b and c public, but I'm guessing you don't want to do that, as it changes the interface of the class.

In response to your question "why is emplace_back better or more efficient than push_back":

By design, emplace_back() should avoid creating a temporary object and should construct "in place" at the end of the vector. With push_back({a, b, c}) you create a temporary MyClass object, which is then copied to the end of the vector. Of course, compiler optimizations may actually lead to same code being generated in both cases, but, by default, emplace_back() should be more efficient. This is further discussed here: push_back vs emplace_back .

Upvotes: 0

AlexD
AlexD

Reputation: 32576

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

Upvotes: 12

Related Questions