Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Using std::transform on a vector of structures

I have a C++ application with a struct which looks like:

struct test_struc {
    std::string name;
    int x;
    int y;
    std::vector<int> data;
};

And I would like to transform two std::vector<test_struc> using the lines according to their data element in the structure. So far, I have the code:

std::vector<test_struc> first = <from somewhere else>;
std::vector<test_struc> second = <from somewhere else>;

std::vector<int> result;
std::transform (second.begin(), second.end(), first.begin(), result.begin(), op_xor);

where op_xor is:

int op_xor (int &i,
            int &j) {
    return  i^j;
}

This works well if first and second are vectors of int, but since they are not, I don't know how to tell the code to use the data element of test_struc as arguments to std::transform.

Am I barking up the wrong tree? Or is there a way to do this?

like image 965
Brett Avatar asked Mar 22 '26 20:03

Brett


2 Answers

Note that at least with a modern compiler, you probably want to implement the operation as a lambda expression, so it would look something like:

std::transform(second.begin(), second.end(), 
               first.begin(),
               std::back_inserter(result),
               [](test_struct const &a, test_struct const &b) { 
                   return a.y ^ b.y; 
               });

Minor aside: as it was, you had UB, trying to write through result.begin() when the size of result was 0. You could either use back_inserter as above, or you could define result initializing its size to second.size().

like image 109
Jerry Coffin Avatar answered Mar 24 '26 11:03

Jerry Coffin


Your binary functor must take two test_structs:

int op_xor (const test_struct& i,
            const test_struct& j) 
{
    return  42; // replace wit your desired logic.
}

It isn't clear what exactly you want the functor to do, but it should operate on the test_structs and return an int.

like image 44
juanchopanza Avatar answered Mar 24 '26 10:03

juanchopanza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!