如何使用 C++11
30 行代码搞定计算 2D 多边形面积?
完整代码如下:
#include <vector>
#include <utility>
using Point = std::pair<double, double>;
double shoelace(const std::vector<Point>& points) {
if (points.size() < 3) {
throw std::invalid_argument("invalid_argument error");
}
// cross-multiplying
auto calc_cross_mul = [](Point p1, Point p2)->double { return p1.first * p2.second - p2.first * p1.second; };
Point it = points.back();
auto area = 0.0;
for (auto& i : points) {
area += calc_cross_mul(it, i);
it = i;
}
return area / 2.0;
}
int main()
{
std::vector<Point> points{ {1,6},{3,1},{7,2},{4,4},{8,5} };
try
{
auto area = shoelace(points);
std::cout << "area: " << area << std::endl; // area: 16.5
}
catch (const std::exception& e)
{
std::cout << e.what() << std::endl;
}
return 0;
}
https://en.wikipedia.org/wiki/Shoelace_formula