在閱讀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的結構體數據類型中,這種方法在工程中很常用。