Smart way to assign one element from vector A to vector B
This is part of the code that I am currently using and I was wondering if there was a more elegant way to do this in C ++ 11 -
Essentially vector_a
copied to vector_b
, then slightly modified, then reverted vector_b
.
Vector elements have a class Point
that is basically (excluding constructors and a bunch of methods):
class Point {
double x,
y,
z;
};
Ideally, I would like to boil down the assignment of the member z
from vector_a
to vector_b
to something like a string or two, but have not been able to think of an elegant way to do it.
Any suggestions are greatly appreciated!
auto localIter = vector_a.begin();
auto outIter = vector_b.begin();
while (localIter != vector_a.end() && outIter != vector_b.end())
{
outIter->z = localIter->z;
localIter++;
outIter++;
}
source to share
A partial copy is just a transformation of elements (one of many) and therefore std::transform
is a natural application here.
As with many algorithms that operate on multiple sequences, you must be careful about the boundaries of your containers; in this particular case, since vector_b
just getting stuff, the easiest thing to do is start empty and adjust its size along the way.
Thus, in the end we get:
vector_b.clear();
std::transform(vector_a.begin(),
vector_a.end(),
std::back_inserter(vector_b),
[](Elem const& a) { Elem b; b.z = a.z; return b; });
transform
is perhaps the most general algorithm in the standard library (it could mimic copy
, for example ), so you should consider carefully while a more specialized algorithm exists before achieving it. In this case, however, it just fits.
source to share
Since the vector has a random access iterator (use std::next
is efficient), I would write the code like this
auto it = vector_a.begin();
std::for_each( vector_b.begin(),
std::next( vector_b.begin(),
std::min( vector_a.size(), vector_b.size() ) ),
[&it] ( Point &p ) { p.z = it++->z; } );
source to share