**Discussion 8** 10/13, 10/15 [(back to course webpage)](./mcs360_fall2020.html) # Class in C++ Let us go back to the bubblegum dispenser problem in [Discussion 2 Part 3](https://homepages.math.uic.edu/~potla/teaching/fall2020/d2.md.html#part3:basicsofaclass) to revisit the basics of writing a class. # Pairs in C++ + A pair in C++ is defined by `std::pair < T, T >` where `T` is any datatype. So, to define a pair of integers, we can write `std::pair < int, int > A;`. + To create a pair, one needs to use the `std::make_pair(*,*)` function. Eg, `std::pair < int, int > A = std::make_pair(4, 10);`. + To access the first element, we use `A.first`. For the second element, we use `A.second`. ## Example Code ```cpp #include #include typedef std::pair < double, double > Point; int main() { std::vector A; A.push_back(std::make_pair(5.2, 10.2)); A.push_back(std::make_pair(1.2, 4.5)); A.push_back(std::make_pair(3.14, 2.71)); std::cout << "The vector of pairs:\n"; for(int i = 0; i < A.size(); i++) { std::cout << "[" << A[i].first << ", " << A[i].second << "]\n"; } return 0; } ``` ## Output of above code: ```bash (base) potla@EKR:~/Desktop/mcs360$ ./d82 [5.2, 10.2] [1.2, 4.5] [3.14, 2.71] ``` ## Sorting A To sort the vector of pairs by their _first_ entries, do: ```cpp std::sort(A.begin(), A.end()) ``` You can then print the vector `A` again to get: ```bash [1.2, 4.5] [3.14, 2.71] [5.2, 10.2] ```
Aside: How to sort by the second elements of the pairs? If we want to sort by the second elements, ie change the vector A to `[3.14, 2.71], [1.2, 4.5], [5.2, 10.2]` we need to define a custom comparison function that compares two points by their second coordinates.
# Discussion Problems ## Problem 1 Write a class `Circle` in C++. It consists of two attributes: `center` and `radius`. `radius` is a double, and `center` is a `std::pair < double, double >` object. It has three functions: `printCenter`, `printRadius`, and `printArea` that print the center, the radius and the area of the circle, respectively. ## Problem 2 Implement a function that shifts the circle around. The function `shift()` takes an `std::pair < double, double >` as input, and `C.shift(std::make_pair(a,b))` will shift the center of the circle `C` by `(a,b)`. ## Problem 3 Implement a function that dilates the circle. The function `dilate()` takes a **nonzero** double $\alpha$ as input, and multiplies the radius by $\alpha$.