在阅读udacity的粒子滤波的代码时,发现读取地图数据的代码(从文件中读取数据存放到自定义的数据结构中)写得还不错,后续可能会在工程中用上,在这里记录下来,以作记录。
首先它定义了地图数据结构:
class Map {
public:
struct single_landmark_s
{
int id_i ; // Landmark ID
float x_f; // Landmark x-position in the map (global coordinates)
float y_f; // Landmark y-position in the map (global coordinates)
};
std::vector<single_landmark_s> landmark_list ; // List of landmarks in the map
};
具体数据文件存放在一个map_data.txt中
92.064 -34.777 1
61.109 -47.132 2
17.42 -4.5993 3
-7.1285 -34.54 4
232.32 32.032 5
177.43 28.083 6
286.89 18.159 7
274.37 31.197 8
主函数中去调用read_map_data()函数:
// Read map data
Map map;
if (!read_map_data("../data/map_data.txt", map))
{
cout << "Error: Could not open map file" << endl;
return -1;
}
然后我们来看看read_map_data()的具体实现:
/* Reads map data from a file.
* @param filename Name of file containing map data.
* @output True if opening and reading file was successful
*/
inline bool read_map_data(std::string filename, Map& map)
{
// Get file of map:
std::ifstream in_file_map(filename.c_str(),std::ifstream::in);
// Return if we can't open the file.
if (!in_file_map) {
return false;
}
// Declare single line of map file:
std::string line_map;
// Run over each single line:
while(getline(in_file_map, line_map)){
std::istringstream iss_map(line_map);
// Declare landmark values and ID:
float landmark_x_f, landmark_y_f;
int id_i;
// Read data from current line to values::
iss_map >> landmark_x_f;
iss_map >> landmark_y_f;
iss_map >> id_i;
// Declare single_landmark:
Map::single_landmark_s single_landmark_temp;
// Set values
single_landmark_temp.id_i = id_i;
single_landmark_temp.x_f = landmark_x_f;
single_landmark_temp.y_f = landmark_y_f;
// Add to landmark list of map:
map.landmark_list.push_back(single_landmark_temp);
}
return true;
}
把数据放到了vecotr的结构体数据类型中,这种方法在工程中很常用。