mardi 28 mars 2017

Fastest Way To std::vector

Here is the test code:

class A{};
class B : public A{};

void Test(const std::vector<A>& a)
{
}

int main()
{
    std::vector<A> a;
    std::vector<B> b;
    Test(a);
    Test(b);//Compiler Error
    return 0;
}

Since std::vector<A> and std::vector<B> is different type, we can't make conversion from one to another.

An optional way can be:

class A{};
class B : public A{};

void Test(const std::vector<A>& a)
{
}

int main()
{
    std::vector<A> a;
    std::vector<B> b;
    Test(a);
    Test(std::vector<A>(b.begin(), b.end()));
    return 0;
}

It acts, but it takes extra copying from B to A. If A or B is a large object, it can be very slow. A better choice is:

class A{};
class B : public A{};

void Test(const std::vector<A>& a)
{
}

int main()
{
    std::vector<A> a;
    std::vector<B> b;
    Test(a);
    Test(std::vector<A>(std::make_move_iterator(b.begin()), std::make_move_iterator(b.end())));
    return 0;
}

Since it just move the iter instead of the whole B class, it take a better performance. But there are some extra cost - If b is a very large vector with huge number of items, iteration also can slow down my code.

So I wonder if there is a way to directly convert std::vector<B> to std::vector<A> without any extra cost?

Aucun commentaire:

Enregistrer un commentaire