Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Vector of Struct to Function

Tags:

c++

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()?

like image 917
Joerg Avatar asked Mar 28 '13 09:03

Joerg


People also ask

How do you pass a vector structure in C++?

You could use std::transform and std::back_inserter to do it.

Can you have a vector of a struct?

You can actually create a vector of structs!

Can you pass a struct by reference in C++?

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.


2 Answers

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
like image 142
borisbn Avatar answered Oct 27 '22 09:10

borisbn


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);
like image 41
Some programmer dude Avatar answered Oct 27 '22 08:10

Some programmer dude