C++从结构体deque提取数据
问题描述:
我得到了一个路点结构体系,我需要提取特定的属性。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"}
答
由于@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中调用每个结构实例。
不,你不能形成在运行时的变量名。另外,'extract(“speed”)'在'extract_speed()'上的优点是什么? –
https://stackoverflow.com/questions/41453/how-can-i-add-reflection-to-a-c-application – Blacktempel