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++;
}

      

+3


source to share


4 answers


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.

+2


source


You can use transform()

.

std::transform (vector_a.begin(), vector_a.end(), vector_b.begin(), vector_a.begin(), [](Elem a, Elem b) { a->z = b->z; return a; });

      



Where Elem

is the type of the vector element.

+4


source


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; } );

      

+3


source


I would be tempted to do something like this:

#include <vector>

struct info
{
    int z;
};

int main()
{
    std::vector<info> a = {{1}, {2}, {3}};
    std::vector<info> b = {{4}, {5}};

    for(size_t i(0); i < a.size() && i < b.size(); ++i)
        b[i].z = a[i].z;
}

      

0


source







All Articles