- Date // ( , , , 1...12 ..).
operator<, Date.
std::map<Date, int> ( int ), " ", Date map-key.
, , Date , string ( , /, "-" ).
( VS2012):
#include <iostream> // for std::cout, std::endl
#include <map> // for std::map
#include <sstream> // for std::ostringstream
#include <string> // for std::string
#include <vector> // for std::vector
using namespace std;
struct Date {
int day;
int month;
int year;
Date() : day(0), month(0), year(0) {}
Date(int d, int m, int y)
: day(d), month(m), year(y)
{}
};
bool operator<(const Date& d1, const Date& d2) {
if (d1.year < d2.year)
return true;
if (d1.year > d2.year)
return false;
if (d1.month < d2.month)
return true;
if (d1.month > d2.month)
return false;
return (d1.day < d2.day);
}
string FormatDate(const Date& date) {
ostringstream os;
if (date.day < 10)
os << '0';
os << date.day;
static const char* monthNames[] = {
"JAN", "FEB", "MAR", "APR",
"MAY", "JUN", "JUL", "AUG",
"SEP", "OCT", "NOV", "DEC"
};
os << monthNames[date.month - 1];
os << date.year;
return os.str();
}
struct Item {
string type;
int price;
Date date;
Item(const string& t, int p, const Date& d)
: type(t), price(p), date(d)
{}
};
int main() {
vector<Item> items;
items.push_back(Item("STRAW", 10, Date(15, 11, 1991)));
items.push_back(Item("TOY", 10, Date(15, 11, 1991)));
items.push_back(Item("BARLEY", 5, Date( 1, 10, 1992)));
map<Date, int> priceData;
for (const auto& item : items) {
auto where = priceData.find(item.date);
if (where != priceData.end()) {
where->second += item.price;
} else {
priceData[item.date] = item.price;
}
}
for (const auto& e : priceData) {
cout << FormatDate(e.first) << " " << e.second << endl;
}
}
:
15NOV1991 20
01OCT1992 5