const Correctness
Completed
Write class Polygon holding points with a const method perimeter(). A free function void report(const Polygon &p) can only call const methods. Read a polygon and report its perimeter (2 decimals) and number of points.
Input
n, then n lines x y.
Output
One line: points=N perimeter=P
Example
Input
4 0 0 3 0 3 4 0 4
Output
points=4 perimeter=14.00
Editor
C++
Hints
Methods that don't modify the object should be marked const.
A const reference can only call const methods.
Solution explanation
const correctness lets the compiler enforce "this function won't change that object".
Show solution
#include <iostream>
#include <iomanip>
#include <vector>
#include <cmath>
using namespace std;
class Polygon {
public:
void add(double x, double y) { pts_.push_back({x, y}); }
size_t size() const { return pts_.size(); }
double perimeter() const {
double total = 0;
for (size_t i = 0; i < pts_.size(); i++) {
const auto &a = pts_[i];
const auto &b = pts_[(i + 1) % pts_.size()];
total += hypot(a.first - b.first, a.second - b.second);
}
return total;
}
private:
vector<pair<double, double>> pts_;
};
void report(const Polygon &p) {
cout << fixed << setprecision(2) << "points=" << p.size() << " perimeter=" << p.perimeter() << "\n";
}
int main() {
int n;
cin >> n;
Polygon p;
for (int i = 0; i < n; i++) {
double x, y;
cin >> x >> y;
p.add(x, y);
}
report(p);
return 0;
}