Re: Using one vector to construct another
On May 29, 3:03 am, Markus Schoder <a3vr6dsg-use...@yahoo.de> wrote:
On Mon, 28 May 2007 15:46:01 -0700, Salt_Peter wrote:
On May 28, 5:28 pm, Chris Roth <czr...@mail.usask.ca> wrote:
I am constructing a vector of objects of class A. The constructor for
class A takes an instance of class B in its constructor. I have a
vector of B objects and would like to construct a vector of A objects
so that each is constructed using the corresponding B object.
Is this possible or do I need to use pointers along with new and
delete?
With std::back_inserter...
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
class B { };
class A {
B m_b;
public:
A(const B& b) : m_b( b ) { }
};
int main()
{
std::vector< B > vb(10);
std::vector< A > va;
std::copy( vb.begin(), vb.end(), std::back_inserter(va) );
}
This of course works only if A's constructor is not explicit.
If A's constructor is not explicit, then:
std::vector< A > va( vb.begin(), vb.end() ) ;
is all that is needed. If A's constructor is explicit, then you
probably need transform and a transforming object, or some sort
of transforming iterator. With transform:
struct XForm
{
A operator()( B const& b ) const
{
return static_cast< A >( b ) ;
}
} ;
std::transform( vb.begin(), vb.end(),
XForm(),
std::back_inserter( va ) ) ;
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34