第九章 9.5.5节练习 & 9.6节练习

来源:互联网 发布:windows closewait 编辑:程序博客网 时间:2024/04/29 23:31

练习9.50:

编写程序处理一个vector<string>,其元素都表示整型值。计算vector中的元素之和。修改程序,使之计算表示浮点值的string之和。

解答:

#include <iostream>#include <string>#include <vector>using namespace std;long myAdd_long(const vector<string>& svec){  long sum = 0;  for(auto i: svec){    sum += stol(i);  }  return sum;}double myAdd_double(const vector<string>& svec){  long sum = 0;  for(auto i: svec){    sum += stol(i);  }  return sum;}int main(){  string mystr1("123");  string mystr2("123999");  vector<string> mystr{mystr1, mystr2};  if ((123 + 123999) == myAdd_long(mystr)){    cout << "Passed" << endl;  }  if (static_cast<double>(123 + 123999) == myAdd_double(mystr)){    cout << "Passed" << endl;  }}


练习9.51:

涉及一个类,他有三个unsigned成员,分表表示年、月和日。为其编写构造函数,几首一个表示richie的string参数。你的构造函数应该能处理不同数据格式,如 January 1,1900、1/1/1990、Jan 1 1900等。

解答:

#include <iostream>#include <sstream>#include <string>#include <vector>using namespace std;const string num_char("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");const string number("0123456789");const vector<string> months{"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};class Data{public:  Data():year(1900), month(1), day(1){};  Data(const string&);  friend ostream& operator<< (ostream& stream, Data& data);  size_t year;  size_t month;  size_t day;};ostream& operator<< (ostream& stream, Data& data){  stream << data.month << " ";  stream << data.day << " ";  stream << data.year << endl;}Data::Data(const string& init_str){  string str = init_str;  string::size_type pos = 0;  string data_store[3];  while((pos = str.find_first_not_of(num_char, pos)) != string::npos){    str.replace(pos, 1, " ");    ++pos;  }  istringstream data(str);  data >> data_store[0];  data >> data_store[1];  data >> data_store[2];  // processing month  pos = 0;  if (data_store[0].find_first_of(number, pos) != string::npos){    month = stoi(data_store[0]);  }  else{    for (int i = 0; i < 12; i++){      if(data_store[0].find(months.at(i)) != string::npos){        month = i + 1;        break;      }    }  }  // processing day  day = stoi(data_store[1]);  // processing year  year = stoi(data_store[2]);}int main(){  Data d1;  Data d2("January 1,1900");  Data d3("1/1/1990");  Data d4("Jan 1 1900");  cout << "d1: " << d1;  cout << "d2: " << d2;  cout << "d3: " << d3;  cout << "d4: " << d4;}

比较繁琐的解决方式,这里也不打算去优化了,功能在这里已经能够完成了,每个代码块完成内容这里的可识别度也还是可以的。

不过。对于string参数初始化,只适应书中列出来那三种。

其他的暂时不去添加了(可能会让程序更麻烦)


练习9.52:

使用stack处理括号化的表达式。当你看到一个左括号,将其记录下来。当你再一个左括号之后看到一个右括号,从stack中pop对象,直至遇到左括号,将左括号也一起弹出栈。然后讲一个值(括号内的运算结果)push到栈中,表示一个括号化的(子)表达式已经处理完毕,被其运算结果所替代。

解答:

这其实就相当与一个课程设计了。

思路:1.将中序表达式转化为后续表达式。2.使用后序表达式进行计算。

这里放个开源项目吧,以后自己也好看。

计算器 abacus 2

0 0
原创粉丝点击