2017-09-04 116 views
0

我得到了一個路點結構體系,我需要提取特定的屬性。C++從結構體deque提取數據

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

但propreties提取在功能之前是不知道的,它取決於需求。 我想一個函數是這樣的:

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

不,你不能形成在運行時的變量名。另外,'extract(「speed」)'在'extract_speed()'上的優點是什麼? –

+0

https://stackoverflow.com/questions/41453/how-can-i-add-reflection-to-a-c-application – Blacktempel

回答

0

由於@Bo在評論

提到你不能在運行時形成的變量名。

但你可以實現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); 

並在deque中調用每個結構實例。

[Live example on Ideone]