Swiss Frank
Swiss Frank

Reputation: 2422

C++11: most efficient way to append a POD to a vector<>

Say I have a little structure with an int, double, and std:string.

I have a vector of these structures.

The efficient C solution would be to allocate the array, then loop through and set the field's values. Each value is only calculated once and is stored where its final resting place is.

In C++11 I can use emplace_back() to avoid creating a temporary structure on the stack then copying it into the vector memory, and deleting the temporary structure. But I'm providing a brace-enclosed initializer list to emplace_back() and compiler complains there's no matching function for call to emplace_back with a brace-enclosed initializer list.

So must I write a three-argument public constructor in this case? And if I did so would it be as efficient as the C version?

Upvotes: 2

Views: 314

Answers (1)

Enlico
Enlico

Reputation: 28416

Since you mention structure instead of class, and since you also mention C, I suspect you have not defined a constructor.

With emplace_back you still construct something; you do it in place, but you do it. So you need to provide the constructor.

#include <iostream>
#include <string>
#include <vector>

struct Foo {
    Foo(int i, double d, std::string s) : i(i), d(d), s(s) {};
    int i;
    double d;
    std::string s;
};

int main() {
    std::vector<Foo> v;
    v.emplace_back(1,2.5,"hello");
    std::cout << v[0].i << ' '
              << v[0].d << ' '
              << v[0].s << ' ';
}

Upvotes: 1

Related Questions