I'm struggling to figure out how to pass a Vector of a Struct to a function in an easy and elegant way. The code looks like this:
struct cube{ double width; double length; double height; };
vector<cube> myVec;
int myFunc(vector<double> &in)
{
// do something here
}
int test = myFunc(myVec.width); // NOT POSSIBLE
So what I want is to pass just the vector of widths to the function and perform some calculations. Is this at all possible or do I have to pass the complete vector fo struct to the function myFunc()?
You could use std::transform and std::back_inserter to do it.
You can actually create a vector of structs!
Structures can be passed by reference just as other simple types. When a structure is passed by reference the called function declares a reference for the passed structure and refers to the original structure elements through its reference. Thus, the called function works with the original values.
If you want to perform some computations with one of the struct's field, then you must tell myFunc
what field it needs to use. Like this:
void myFunc( std::vector< cube > & vect, double cube::*field ) {
for ( cube & c : vect ) {
c.*field // <--- do what you want
}
}
// calling
myFunc( myVect, & cube::width );
myFunc( myVect, & cube::length );
// etc.
BTW, even if fields are different type, but they can be used in formula inside myFunc
, you still can use myFunc
by making it template:
template< typename FieldType >
void myFunc( std::vector< cube > & vect, FieldType cube::*field ) {
for ( cube & c : vect ) {
c.*field // <--- do what you want
}
}
// calling will be similar to the first piece
You have to create a new vector containing all the width
elements in the myVec
vector.
You could use std::transform
and std::back_inserter
to do it.
std::vector<cube> myVec;
std::vector<double> myWidthVector;
std::transform(std::begin(myVec), std::end(myVec),
std::back_inserter(myWidthVector),
[](const cube& c) { return c.width; });
myFunc(myWidthVector);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With