#pragma once ///////////////////////////////////////////////////////////////////// // PointsCollection.h - Create and Operate on collections of Points // // Jim Fawcett, CSE687-OnLine, Summer 2017 // #include "../PointsProcessing/Points.h" #include #include ///////////////////////////////////////////////////////////////////// // PointsCollection class // - Supports creating and operating on collections of points. // - Uses an underlying std::vector> to store its // collection of points. // - Provides a member function accepting any callable object. // That allows users to do almost any kind of operation on // each member of the collection. // - All of this is demonstrated in the test stub. template class PointsCollection { public: using iterator = typename std::vector>::iterator; using Callable = std::function& t)>; PointsCollection(const std::string& name = "") : name_(name) {} void add(const Point& point) { points_.push_back(point); } std::string& name() { return name_; } typename iterator begin() { return points_.begin(); } typename iterator end() { return points_.end(); } void doOp(Callable oper); void show(bool expand = false); private: std::vector> points_; std::string name_; }; /*----< operate on each point with callable function >-------------*/ template void PointsCollection::doOp(Callable oper) { for (Point& point : points_) { oper(point); } //--------------------------------------------------------- // The code below, using the collection iterator directly, // is equivalent to that above. //--------------------------------------------------------- // for (iterator iter = begin(); iter != end(); ++iter) // { // oper(*iter); // } //--------------------------------------------------------- } /*----< display collection >---------------------------------------*/ /* * - send values of points in collection to std::cout * - expand determines whether each point is given its own line * - note that show uses doOp, a demonstration of how to use that * facility */ template void PointsCollection::show(bool expand) { bool first = true; std::function&)> proc = [&first, expand](Point& p) { if (first) { first = false; std::cout << "\n " << p.toString(); } else { if (expand) { std::cout << "\n " << p.toString(); } else { std::cout << ", " << p.toString(); } } }; doOp(proc); }