1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
|
#include <iostream>
#include <ostream>
#include <set>
#include <string>
// let's not use "list" as name, because this won't be a list
struct Packet {
int password, day, month, year;
float price;
std::string name; // easier to use
// constructor for "default" object, uses initializer lists
Packet():
password(0),
day(23),
month(12),
year(2011),
price(12.0f),
name("Cake")
{
}
// constructor for writing less code initializing new objects
Packet(int password, int day, int month, int year, float price, const std::string &name):
password(password),
day(day),
month(month),
year(year),
price(price),
name(name)
{
}
// this comparison operator will be used automatically by std::set
bool operator < (const Packet &p) const
{
if (password == p.password) // same password,
return name < p.name; // so compare names
return password < p.password;
}
};
// this teaches std::cout to print Packet objects
std::ostream & operator << (std::ostream &os, const Packet &p)
{
os << "Packet at memory address " << &p << " contains:";
os << "\npassword: ....... " << p.password;
os << "\nday, month, year: " << p.day << ' ' << p.month << ' ' << p.year;
os << "\nprice: .......... " << p.price;
os << "\nname: ........... " << p.name;
os << std::endl;
return os;
}
int main()
{
// declare the Packets
Packet p1(331, 1, 12, 1998, 5.0f, "Zap Cola");
Packet p2(331, 2, 12, 1998, 5.1f, "Pepsi");
Packet p3(983, 12, 3, 2012, 12.0f, "Hamburger");
Packet p4(10, 3, 2, 2001, 2.0f, "Hot dog");
// Set containing Packets
std::set<Packet> sp;
// add our objects to the Set
sp.insert(p1);
sp.insert(p2);
sp.insert(p4);
sp.insert(p3);
sp.insert(Packet(983, 12, 3, 2012, 14.0f, "Cheeseburger")); // this works too
// display the Packets in the Set
for (std::set<Packet>::const_iterator ci = sp.begin(); ci != sp.end(); ++ci)
std::cout << *ci << std::endl;
}
|