📄 sortstocks.cpp
字号:
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
#include "tvector.h"
#include "strutils.h" // for atoi and atof
#include "prompt.h"
#include "sortall.h"
#include "stock.h"
struct PriceComparer // compares using price
{
int compare(const Stock& lhs, const Stock& rhs) const
{ if (lhs.price < rhs.price) return -1;
if (lhs.price > rhs.price) return +1;
return 0;
}
};
struct VolumeComparer // compares using volume of shares traded
{
int compare(const Stock& lhs, const Stock& rhs) const
{ if (lhs.shares < rhs.shares) return -1;
if (lhs.shares > rhs.shares) return +1;
return 0;
}
};
void Read(tvector<Stock>& list, const string& filename)
// post: stocks from filename read into list
{
ifstream input(filename.c_str());
string symbol, exchange, price, shares;
while (input >> symbol >> exchange >> price >> shares)
{ list.push_back(Stock(symbol,exchange,atof(price),atoi(shares)));
}
}
void Print(const tvector<Stock>& list, ostream& out)
// post: stocks in list printed to out, one per line
{
int k,len = list.size();
out.precision(3); // show 3 decimal places
out.setf(ios::fixed);
for(k=0; k < len; k++)
{ out << list[k].symbol << "\t" << list[k].exchange << "\t"
<< setw(8) << list[k].price << "\t" << setw(12)
<< list[k].shares << endl;
}
}
int main()
{
string filesymbol = PromptString("stock file ");
tvector<Stock> stocks;
Read(stocks,filesymbol);
Print(stocks,cout);
cout << endl << "----" << endl << "# stocks: " << stocks.size() << endl;
cout << "----sorted by price----" << endl;
InsertSort(stocks,stocks.size(), PriceComparer());
Print(stocks,cout);
cout << "----sorted by volume----" << endl;
InsertSort(stocks,stocks.size(), VolumeComparer());
Print(stocks,cout);
return 0;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -