"Matthias" <no****@digitalraid.com> wrote in message
news:cu*************@news.t-online.com...
Hi,
say I have a vector v1:
std::vector<SomeType> v1;
and I need a vector v2 of pointers to v1's elements:
std::vector<SomeType*> v2;
std::vector<SomeType>::iterator iter;
for( iter = v1.begin(); iter != v1.end(), ++iter )
v2.push_back( &(*iter) );
Now is there a more elegant way to initialize v2 instead of looping
through v1 and pushing back the *iter's address to v2?
Something like "for each elem in v1 insert its address into v2"?
Having a loop which only consists of a single insert operation, I have
the feeling this may be better expressed with some STL algo.
You could use 'std::for_each()' with a functor, but imo it's
probably not worth the trouble. You might just want to wrap
that loop up into a function with references to the two vectors
as parameters, then just call from your 'main' logic. Here's the
'for_each' code just for fun anyway:
#include <algorithm>
#include <vector>
class ftor
{
std::vector<int*>& v;
public:
ftor(std::vector<int*>& arg) : v(arg)
{
}
void operator()(int& i)
{
v.push_back(&i);
}
};
int main()
{
std::vector<int> vec;
for(int i = 0; i < 5; ++i)
vec.push_back(i);
std::vector<int*> pvec;
std::for_each(vec.begin(), vec.end(), ftor(pvec));
return 0;
}
Another possiblity (if your element type is user-defined), is
to define a conversion from T to T*, and use 'std::copy' (not
possible if the element type is a built-in type):
#include <algorithm>
#include <vector>
class C
{
public:
operator C*()
{
return this;
}
};
int main()
{
std::vector<C> cvec;
for(int i = 0; i < 5; ++i)
{
cvec.push_back(C());
}
std::vector<C*> pvec;
std::copy(cvec.begin(), cvec.end(),
std::back_inserter(pvec));
return 0;
}
However I consider this dangerous, as the automatic conversion
from C to C* could mask errors elsewhere.
Having said all the above, BE WARNED: No matter which way you
store your pointers (with a 'plain' loop, either of the ways
I've shown, or any other way), note that if you later modify
the vector of whose elements you're storing their addresses,
and the vector is later modified, the elements could be moved
due to reallocation, invalidating the address values stored
in the other vector. I'd consider doing what you're
asking about only if the first vector is const (in which
case you'd have to load it via a ctor, since you wouln't
be able to 'push_back' the elements. Or if it's not const,
you'd need to reset and reload the pointer vector every time
the first vector gets changed. An awful lot of work. :-)
-Mike