您的位置:首页 > 编程语言 > C语言/C++

《C++ Primer》习题

2016-04-26 19:59 441 查看

类的设计

#include <algorithm>
#include <cctype>
#include <cmath>
#include <fstream>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>
using namespace std;

//----------------------------------------
class Person {
friend istream &read(istream &is, Person &p);
friend ostream &print(ostream &os, const Person &p);

private:
string name;
string addr;

public:
Person(const string &n, const string &a) : name(n), addr(a) {}
Person() = default;
Person(istream &is) { read(is, *this); }

string getName() const { return name; }
string getAddr() const { return addr; }
};

istream &read(istream &is, Person &p) {
is >> p.name >> p.addr;
return is;
}
ostream &print(ostream &os, const Person &p) {
os << p.name << " " << p.addr;
return os;
}

//-----------------------------------------
class Screen;

class Window_mgr {
private:
vector<Screen> screens;

public:
using ScreenIndex = vector<Screen>::size_type;
ScreenIndex addScreen(const Screen &);
void clear(ScreenIndex);
};

Window_mgr::ScreenIndex Window_mgr::addScreen(const Screen &s) {
screens.push_back(s);
return screens.size() - 1;
}

//-----------------------------------------
class Screen {
friend void Window_mgr::clear(ScreenIndex);

public:
typedef string::size_type pos;
Screen() = default;
Screen(pos ht, pos wd) : height(ht), width(wd), contents(ht * wd, ' ') {}
Screen(pos ht, pos wd, char c)
: height(ht), width(wd), contents(ht * wd, c) {}

char get() const { return contents[cursor]; }
char get(pos r, pos c) const;
Screen &move(pos r, pos c);
void some_member() const;
pos Size() const;

Screen &set(char c) {
contents[cursor] = c;
return *this;
}
Screen &set(pos r, pos col, char ch) {
contents[r * width + col] = ch;
return *this;
}

void do_display(ostream &os) const { os << contents << endl; }
Screen &dispaly(ostream &os) {
do_display(os);
return *this;
}
const Screen &display(ostream &os) const {
do_display(os);
return *this;
}

private:
pos cursor = 0;
pos height = 0, width = 0;
string contents;
mutable size_t accese_ctr;
};

char Screen::get(pos r, pos c) const {
pos row = r * width;
return contents[row + c];
}

Screen &Screen::move(pos r, pos c) {
pos row = r * width;
cursor = row + c;
return *this;
}

void Screen::some_member() const { ++accese_ctr; }

Screen::pos Screen::Size() const { return width * height; }

void Window_mgr::clear(ScreenIndex i) {
Screen &s = screens[i];
s.contents = string(s.height * s.width, '-');
}

//----------------------------------------
class Sales_data {
friend istream &read(istream &is, Sales_data &item);
friend ostream &print(ostream &os, Sales_data &item);

public:
// Sales_data() = default;
Sales_data(const string &s, unsigned n, double p)
: bookNo(s), units_sold(n), revenue(n * p) {
cout << "constructing" << endl;
}
Sales_data() : Sales_data("a", 0, 0.0f) {
cout << "delegating constructor" << endl;
}
Sales_data(string s) : Sales_data(s, 0, 0.0f) {}
Sales_data(istream &is) : Sales_data() { read(is, *this); }
string isbn() const { return bookNo; }

private:
float avg_price() const { return units_sold > 0 ? revenue / units_sold : 0; }

private:
string bookNo;
unsigned units_sold;
double revenue;
};

istream &read(istream &is, Sales_data &item) {
double price = 0;
is >> item.bookNo >> item.units_sold >> price;
item.revenue = item.units_sold * price;
return is;
}

ostream &print(ostream &os, Sales_data &item) {
os << item.isbn() << " " << item.units_sold << "" << item.revenue << " "
<< item.avg_price() << endl;
return os;
}

//---------------------------------------
class Account {
public:
void caculate() { amount += amount * interestRate; }
static double rate() { return interestRate; }
static void rate(double);

private:
string owner;
double amount;
static double interestRate;
static constexpr double todayRate = 40.2;
static double initRate() { return todayRate; };
};

void Account::rate(double newRate) { interestRate = newRate; }
double Account::interestRate = initRate();

//--------------------------------------
class wy_Date {
public:
wy_Date(const std::string &s);
unsigned year;
unsigned month;
unsigned day;
};

wy_Date::wy_Date(const std::string &s) {
unsigned format = 0;

//! 1/1/1900
if (s.find_first_of("/") != std::string::npos)
format = 0x10;

//! Jan 1, 1900
if (s.find_first_of(",") >= 4 && s.find_first_of(",") != std::string::npos)
format = 0x01;

switch (format) {

//! format = 1/1/1900
case 0x10:
day = std::stoi(s.substr(0, s.find_first_of("/")));
month = std::stoi(s.substr(s.find_first_of("/") + 1,
s.find_first_of("/") - s.find_last_of("/")));
year = std::stoi(s.substr(s.find_last_of("/") + 1, 4));
break;

//! format = January 1, 1900  or Jan 1, 1900
case 0x01:
day = std::stoi(
s.substr(s.find_first_of("1234567890"),
s.find_first_of(",") - s.find_first_of("1234567890")));

if (s.find("Jan") < s.size())
month = 1;
if (s.find("Feb") < s.size())
month = 2;
if (s.find("Mar") < s.size())
month = 3;
if (s.find("Apr") < s.size())
month = 4;
if (s.find("May") < s.size())
month = 5;
if (s.find("Jun") < s.size())
month = 6;
if (s.find("Jul") < s.size())
month = 7;
if (s.find("Aug") < s.size())
month = 8;
if (s.find("Sep") < s.size())
month = 9;
if (s.find("Oct") < s.size())
month = 10;
if (s.find("Nov") < s.size())
month = 11;
if (s.find("Dec") < s.size())
month = 12;

year = std::stoi(s.substr(s.find_last_of(" ") + 1, 4));
break;
}
}

int main() {
Screen myScreen(5, 5, 'X');
const Screen conScreen(5, 5, 'Y');
myScreen.move(4, 0).set('#').dispaly(cout);

// cout << myScreen.Size() << endl;
// cout << endl;
myScreen.display(cout);
// cout << endl;
conScreen.display(cout);
// cout << endl;
Window_mgr manager;
int i = manager.addScreen(myScreen);
int j = manager.addScreen(conScreen);
manager.clear(0);
myScreen.dispaly(cout);
// cout << endl;

Sales_data item("bcd", 2, 5.0);
Sales_data item1;
Sales_data item2 = {"nb1231", 25, 15.99};
print(cout, item2);

Account account;
Account *ap = &account;
// account.initRate();
cout << ap->rate() << endl;
Account acc1;
cout << acc1.rate() << endl;

wy_Date d("99/21/3871");

std::cout << d.day << " " << d.month << " " << d.year << " ";

// double Account::interestRate = initRate();
}


STL操作

#include <algorithm>
#include <cctype>
#include <cmath>
#include <forward_list>
#include <fstream>
#include <iostream>
#include <iterator>
#include <list>
#include <string>
#include <vector>
using namespace std;

void TextToVec(const string FileName, vector<string> &vec) {
ifstream is(FileName);
string buf;
if (is) {
while (getline(is, buf))
vec.push_back(buf);
}
}

void TextToWord(const string FileName, vector<string> &vec) {
ifstream ifs(FileName);
string buf;
if (ifs) {
while (ifs >> buf)
vec.push_back(buf);
}
}

bool Find(vector<int>::iterator begin, vector<int>::iterator end, int n) {

for (; begin != end; begin++) {
if (*begin == n)
return true;
}
if (begin == end)
return false;
}

void insertString(forward_list<string> &flstr, const string &str1,
const string &str2) {
auto curr = flstr.begin();
int flag = 0;
while (curr != flstr.end()) {
if (*curr == str1) {
curr = flstr.insert_after(curr, str2);
flag = 1;
}
curr++;
}
if (!flag)
curr = flstr.insert_after(curr, str2);
}

void Replace(string &s, const string oldVal, const string newVal) {
for (auto beg = s.begin(); beg != s.end(); beg++) {
if (*beg == s.front())
continue;
if (distance(beg, s.end()) < distance(oldVal.begin(), oldVal.end()))
break;
if (string{beg, beg + oldVal.size()} == oldVal) {
auto pos = distance(s.begin(), beg);
/*s.erase(beg, beg + oldVal.size());
s.insert(beg, newVal.begin(), newVal.end());*/
s.replace(beg, beg + oldVal.size(), newVal.begin(), newVal.end());
beg = std::next(s.begin(), pos + newVal.size() - 1);
}
}
}

double cacculate(const vector<string> &vec) {
int sum = 0;
for (auto const &s : vec)
sum += stoi(s);
return sum;
}

int main(int argc, char const *argv[]) {
vector<string> vs = {"my", "name", "is", "zoe"};
double sum = cacculate(vs);
cout << sum << endl;
for (size_t i = 0; i < vs.size(); i++) {
cout << vs[i] << " ";
}
cout << endl;
vs.insert(vs.begin(), "hello");
for (size_t i = 0; i < vs.size(); i++) {
// cout << vs[i] << " ";
}
cout << endl;
list<string> lst;
lst.insert(lst.begin(), vs.begin(), vs.begin() + 2);
for (auto iter = lst.begin(); iter != lst.end(); iter++) {
// cout << *iter << " ";
}
auto result = find(vs.begin(), vs.end(), "zoe");
/*cout << "the position" << (*result)
<< (result == vs.cend() ? "is not present" : "is present") << endl;
int size = vs.size();
cout << size << endl;*/

forward_list<int> flst = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
auto prev = flst.before_begin();
auto curr = flst.begin();
while (curr != flst.end()) {
if (*curr % 2)
curr = flst.erase_after(prev);
else {
prev = curr;
++curr;
}
}
forward_list<string> flstr = {"I",      "love", "my", "cat",
"deeply", "do",   "you"};
string str1{"cat"};
string str2{"dog"};
insertString(flstr, str1, str2);
/*for (auto i = flstr.begin(); i != flstr.end(); i++)
cout << *i << " ";*/
std::vector<std::string> v;
std::string word;

/*while (std::cin >> word) {
v.push_back(word);
std::cout << v.capacity() << "\n";
}*/
string s{"To drive straight thru is a foolish, tho courageous act"};
Replace(s, "thru", "through");
Replace(s, "tho", "though");
std::cout << s << std::endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: