Reduce memory usage?

J

Joseph Turian

Let's say I have a vector of Base.
I want to convert it to a vector of Derived, where
Derived::Derived(const Base&); is defined.

Is it possible to convert the vector of Base to a vector of Derived
without incurring the memory overhead of two copies of everything? If
these were vectors of the same kind, I could just use vector::swap, but
unfortunately not in this example.

Joseph
 
?

=?ISO-8859-1?Q?Stefan_N=E4we?=

Joseph said:
Let's say I have a vector of Base.

I want to convert it to a vector of Derived, where
Derived::Derived(const Base&); is defined.

Is it possible to convert the vector of Base to a vector of Derived
without incurring the memory overhead of two copies of everything? If
these were vectors of the same kind, I could just use vector::swap, but
unfortunately not in this example.

Maybe something like this:

1. Define a (template) functor that returns dynamic_cast<Derived*>(p) in operator()(const Base* p)
2. use std::transform(v.begin(), v.end(), v.begin(), CastingFunctor<...>())

/S
 
?

=?ISO-8859-1?Q?Stefan_N=E4we?=

Stefan said:
Maybe something like this:

1. Define a (template) functor that returns dynamic_cast<Derived*>(p) in operator()(const Base* p)
2. use std::transform(v.begin(), v.end(), v.begin(), CastingFunctor<...>())

This must of course be:

std::transform(v.begin(), v.end(), w.begin(), CastingFunctor<...>())

Where w is a (large enough!) vector<Derived*>

/S
 
?

=?ISO-8859-1?Q?Stefan_N=E4we?=

Oops...
This must be:
1. Define a (template) functor that returns dynamic_cast said:
This must of course be:

std::transform(v.begin(), v.end(), w.begin(), CastingFunctor<...>())

Where w is a (large enough!) vector<Derived*>

This might work for you:

<----CODE---->

#include <iostream>
#include <iterator>
#include <string>
#include <algorithm>
#include <vector>

template<typename To>
struct CastingFunctor
{
template<typename From>
To* operator()(From* p) const { return dynamic_cast<To*>(p); }
};

struct Base
{
virtual ~Base() { }
};

struct Derived : public Base
{
};

int main(int argc, char* argv[])
{
const size_t N = 10;
std::vector<Base*> v;

for(size_t i=0; i<N; ++i)
{
v.push_back(new Derived);
v.push_back(new Base);
}

std::vector<Derived*> w(v.size());
std::transform(v.begin(), v.end(), w.begin(), CastingFunctor<Derived>());

std::copy(v.begin(), v.end(), std::eek:stream_iterator<void*>(std::cout, "\n"));
std::copy(w.begin(), w.end(), std::eek:stream_iterator<void*>(std::cout, "\n"));
return 0;
}

<----/CODE---->


/S
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,906
Latest member
SkinfixSkintag

Latest Threads

Top