Reputation: 745
I'm trying to convert a std::set<B>
to std::set<A>
, where:
class A {
}
class B : public A {
}
What's the fastest/most efficient way to do this?
Upvotes: 0
Views: 145
Reputation: 45675
There is no constant-time approach for this*. The best you can get is by using std::copy
or the constructor of std::set
taking two iterators (aka "range constructor").
std::set<B> bs = ...;
std::set<A> as(bs.begin(), bs.end());
*There's a fast but unsafe way to convert it in constant time in the case of sizeof(B) == sizeof(A)
(that is, class B
doesn't introduce new members) and if the classes don't use virtual tables (have virtual functions): You could use an unsafe cast. But only do this if you know what you're doing very well (it's still undefined behaviour but your compiler might do it as expected). The same holds for the case when you use pointers and when the pointers don't need to be offset (which might be the case when using multiple inheritance or some other cases depending on your compiler).
Upvotes: 2