转换包含向量 C++ 的语法和结构

transform syntax and structures containing vectors c++

本文关键字:语法 结构 C++ 包含 向量 转换      更新时间:2023-10-16

我对函数std::transform的语法有问题。因此,我有一个包含有关机场信息的结构AirportInfo。然后,每个结构都排列在字典中,以便它们具有唯一的ID。在结构中有一个对向量m_routes其中包含目的地机场的 ID 以及航班是否直达。 (在这种情况下,只考虑直飞航班,因为所有非直飞航班都已删除,因此对的第二项将始终为 0(。该函数calculateDistanceBetween通过了解它们的坐标来返回 2 个机场之间的距离,这些坐标也存储在pos的结构中。现在我必须计算每条路线的距离,但我无法克服语法:(任何帮助将不胜感激,谢谢!

这段代码有效

// Calculates the distance between two points on earth specified by longitude/latitude.
// Function taken and adapted from http://www.codeproject.com/Articles/22488/Distance-using-Longitiude-and-latitude-using-c
float calculateDistanceBetween(float lat1, float long1, float lat2, float long2)
{
// main code inside the class
float dlat1 = lat1 * ((float)M_PI / 180.0f);
float dlong1 = long1 * ((float)M_PI / 180.0f);
float dlat2 = lat2 * ((float)M_PI / 180.0f);
float dlong2 = long2 * ((float)M_PI / 180.0f);
float dLong = dlong1 - dlong2;
float dLat = dlat1 - dlat2;
float aHarv = pow(sin(dLat / 2.0f), 2.0f) + cos(dlat1) * cos(dlat2) * pow(sin(dLong / 2), 2);
float cHarv = 2 * atan2(sqrt(aHarv), sqrt(1.0f - aHarv));
// earth's radius from wikipedia varies between 6,356.750 km and 6,378.135 km
// The IUGG value for the equatorial radius of the Earth is 6378.137 km
const float earth = 6378.137f;
return earth * cHarv;
}
struct AirportInfo
{
std::string m_name;
std::string m_city;
std::string m_country;
float pos[2]; // x: latitude, y: longitude
std::vector<std::pair<int, int>> m_routes; // dest_id + numStops
std::vector<float> m_routeLengths;
float m_averageRouteLength;
};

以下是导致麻烦的原因:

//- For each route in AirportInfo::m_routes, calculate the distance between start and destination. Store the results in AirportInfo::m_routeLengths. Use std::transform() and calculateDistanceBetween().
void calculateDistancePerRoute(std::map<int, AirportInfo>& airportInfo)
{   //loop all structures 
for(int i = 0; i < airportInfo.size(); i++ ){
// START                        END                                         SAVE 
std::transform(airportInfo[i].pos[0], airportInfo[i].pos[1], /*...*/ , airportInfo[i].m_routeLengths.begin(), 
calculateDistanceBetween);
}
std::cout << "Calculate distance for each route" << std::endl;
} 

使用std::back_inserter(airportInfo[i].m_routeLengths)(如果性能很重要,请提前保留向量大小(,而不是airportInfo[i].m_routeLengths.begin()。此外,当没有任何"强制"说明映射中的猥亵来自0...map.size()是不安全的时,按索引迭代是不安全的,您应该更喜欢在所示用例中使用向量。

我认为这就像你想要的:

void calculateDistancePerRoute(std::map<int, AirportInfo>& airportInfo)
{
for(int i = 0; i < airportInfo.size(); i++ )
{
float currentPosX = airportInfo.at(i).pos[0];
float currentPosY = airportInfo.at(i).pos[1];
std::transform(airportInfo.begin(), airportInfo.end(), std::back_inserter(airportInfo.at(i).m_routeLengths), [&] (const auto& otherAirport)
{
return calculateDistanceBetween(currentPosX, currentPosY, otherAirport.second.pos[0], otherAirport.second.pos[1]);
});
}
}

Godbolt 中的示例