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
|
#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>
class Stock
{
public:
enum Sector { Technology, Health, Financial, Consumer_Goods, Utilities }; //static
enum Status { GAIN, LOSS, BREAKEVEN };
private:
std::string symbol = "AAA";
std::string company;
Sector sctr = Technology ;
Status status = BREAKEVEN ;
int num_shares = 0 ;
// etc.
public:
Stock() = default ;
Stock( std::string symbol, std::string company, Sector sector, Status status, int num_shares )
: symbol(symbol), company(company), sctr(sector), status(status), num_shares(num_shares) {}
Sector sector() const { return sctr ; }
// ...
friend std::ostream& operator<< ( std::ostream& stm, const Stock& stk )
{
static const std::string sector_names[] = { "Technology", "Health", "Financial", "Consumer_Goods", "Utilities" };
return stm << "Stock{ symbol:" << stk.symbol
<< ", company:" << stk.company
<< ", sector: " << sector_names[ stk.sector() ]
<< ", num shares:" << stk.num_shares << " }" ;
}
};
int main()
{
Stock my_stocks[]
{
{ "RDEN", "Elizabeth Arden Inc", Stock::Financial, Stock::GAIN, 500 },
{ "AVP", "Avon Products Inc", Stock::Consumer_Goods, Stock::BREAKEVEN, 650 },
{ "BAC", "Bank of America Corp", Stock::Financial, Stock::LOSS, 1000 },
{ "WFC", "Wells Fargo & Co", Stock::Health, Stock::GAIN, 300 },
{ "VISA", "Visa", Stock::Financial, Stock::GAIN, 700 },
{ "RPTP", "Raptor Pharmaceutical Corp", Stock::Health, Stock::LOSS, 250 }
};
std::sort( std::begin(my_stocks), std::end(my_stocks), // sort ascending on sector
[] ( const Stock& a, const Stock& b ) { return a.sector() < b.sector() ; } ) ;
std::cout << "list of my stocks sorted on sector:\n-----------------------------\n" ;
Stock::Sector prev_sector = Stock::Sector(88) ;
for( const Stock& stk : my_stocks )
{
if( stk.sector() != prev_sector )
{
std::cout << '\n' ;
prev_sector = stk.sector() ;
}
std::cout << stk << '\n' ;
}
}
|