C ++从结构的双端队列中提取数据

C++ extracting data from deque of struct

我得到了路点结构的双端队列,我需要提取特定的属性。

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

例如我得到了

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
...

如果我需要 speed_ms 属性,我想取回一个数组,如:

0.00
0.00
0.00
...

但提取的属性在功能之前是未知的,这取决于需要。 我在想这样的功能:

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

正如@Bo 在评论中提到的那样

you cannot form variable names at runtime.

但是您可以为结构的每个成员实现 get 函数

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

那么模板包装函数就可以解决你的问题

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

然后用你需要的变量的get函数调用这个包装器

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

并在双端队列中的每个结构实例上调用它。

[Live example on Ideone]