简体   繁体   中英

C++ extracting data from deque of struct

I got a deque of way-point struct, and i need to extract an specific properties.

struct way_point
{
double time_stamp_s; 
double lat_deg; 
double  long_deg; 
double height_m; 
double roll_deg;
double pitch_deg; 
double yaw_deg; 
double speed_ms; 
double pdop; 
unsigned int gps_nb; 
unsigned int glonass_nb; 
unsigned int beidou_nb;
};

for example i got

28729.257 48.66081132 15.63964745 322.423 1.1574 4.8230 35.3177 0.00 0.00 0 0 0
28731.257 48.66081132 15.63964744 322.423 1.1558 4.8238 35.3201 0.00 1.15 9 6 0
28733.257 48.66081132 15.63964745 322.423 1.1593 4.8233 35.3221 0.00 1.15 9 6 0
...

and if I need for example the speed_ms properties, i would like to get back an array like :

0.00
0.00
0.00
...

but the propreties to extract isn't known before the fonction, it's depending for the need. I was thinking of a function like this :

function extract (string propertie_to_extract = "speed_ms", deque<struct way_point> way_point){
retrun vector[i]=way_point[i]."propertie_to_extract"}

As @Bo mentioned in comments

you cannot form variable names at runtime.

But you may implement get-functions for every member of structure

double Get_time_stamp_s(way_point& wp) { return wp.time_stamp_s; }
double Get_gps_nb      (way_point& wp) { return wp.gps_nb;       }
// Rest of get-functions

Then templated wrapper function can solve your problem

template<typename T>
T getData(std::function<T(way_point&)> f, way_point& wp)
{
    return f(wp);
}

And call this wrapper with get-function of variable you need

way_point wp { 1.0, 2 };
double       time_stamp_s_value = getData<double>(Get_time_stamp_s, wp);
unsigned int gps_nb_value       = getData<unsigned int>(Get_gps_nb, wp);

And call it on every structure instance in deque.

[Live example on Ideone]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM