Create a vector of char which stores the letters of the alphabet in order. Print the elements of the vector in order and in reverse order using std::copy and a stream iterator. Save the result in a file named "vector_q1.cpp".
Get the files inventory.h and inventory.cpp. In file "inventory.h", two classes are defined: Item and Inventory. An item is simply identified by its id. An inventory contains a list of items which are in stock (in_stock)) and a list of ids corresponding to items that have already been ordered (ordered). There are two methods used to manipulate an inventory: order() and shipped():
Output for the example code in main() should be:
Order for 1 received. Not in stock. Ordering item with id 1 Order for 2 received. Not in stock. Ordering item with id 2 Received shipment of item with id 1 1 was ordered by customer. Ship it. Received shipment of item with id 2 2 was ordered by customer. Ship it.
Your goal for this exercise will be to write a function object that will be used to sort two dimensional points in a vector of points according to their distance to the origin.
The distance to the origin for a point p of coordinates (x,y) is given by Sqrt(x^2 + y^2). The method norm() in the class Point_2d is computing that distance for you.
// test_function_algorithms.cpp
#include <algorithm>
#include <vector>
#include <cmath>
#include <ostream>
class Point_2d {
public:
Point_2d(double x, double y) : x_(x), y_(y) {}
double norm() const { return sqrt(x_*x_ + y_*y_); }
double x() const { return x_; }
double y() const { return y_; }
private:
double x_, y_;
};
std::ostream& operator<< (std::ostream& os, const Point_2d& p)
{
os << "(" << p.x() << ", " << p.y() << ")" << std::endl;
return os;
}
// Function object to compare Point_2d according to their distance
// to the origin.
// Example of use:
// Less_Point_2d less;
// Point_2d p1(1.0, 2.0), p2(2.0, 2.0);
// bool t = less(p1, p2); // t == true;
class Less_Point_2d {
// complete the code to turn this class into a function object
// according to the example above
};
int main()
{
Point_2d p1(0.0, 0.0), p2(1.0, 2.0);
Point_2d p3(2.0, 2.0), p4(1.5, 1.5);
Point_2d p5(0.5, 1.5);
std::vector<Point_2d> v;
v.push_back(p1); v.push_back(p2);
v.push_back(p3); v.push_back(p4);
v.push_back(p5);
Less_Point_2d less;
sort(/* complete the argument of sort() such that v is sorted by dist to origin */);
std::vector<Point_2d>::iterator it;
for (it = v.begin(); it != v.end(); it++)
{
std::cout << *it << std::endl;
}
}