C++primer9.5节练习

2022/7/21 1:23:47

本文主要是介绍C++primer9.5节练习,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

练习9.41

编写程序,从一个vector<char>初始化一个string。

 1 #include<iostream>
 2 #include<vector>
 3 #include<string>
 4 int main()
 5 {
 6     std::cout<<"hello,sir"<<std::endl;
 7     std::vector<char> a(10,'a');
 8     std::string b(&a[0],2);
 9     std::cout<<b<<std::endl;
10 }

练习9.42

假定你希望每次读取一个字符存入一个string中,而且知道最少需要读取100个字符,应该怎样提高程序性能

c.reserve(100);

练习9.43

编写一个函数,接受三个string参数s,oldVal和newVal,使用迭代器及insert和erase函数将s中所有oldVal替换成newVal

1 void replace(string &s,string &oldVal,string &newVal)
2 {
3     for(string::size_type d=0;*d!=s.size();++d)
4         {
5                 if(s.substr(d,oldVal.isze()==oldVal)
6                      {
7                           s.erase(d,oilVal.size());
8                            s.insert(d,newVal);}}}     

练习9.44

重写上题,改用下标和replace

void replace(string &s,string &oldVal,string &newVal)
2 {
3     for(string::size_type d=0;*d!=s.size();++d)
4         {
5                 if(s.substr(d,oldVal.isze()==oldVal)
6                      {
7                           s.replace(d,oldVal.size(),newVal);}}}    

练习9.45

编写一个函数,接受一个表示名字的string参数和两个分别表示前缀和后缀的字符串添加到给定的名字中,将新生成的string返回

string func(string& s, const string& prefix,const string& endfix)
{
    s.insert(0,prefix);
    s.append(endfix);
    return s;
}

练习9.46

重写上题函数,使用位置和长度管理string,只使用insert

1 string func(string& s, const string& prefix,const string& endfix)
2 {
3     s.insert(0,prefix);
4     s.insert(s.size(),endfix);
5     return s;
6 }
7  

练习9.47

编写程序,首先查找string“ab2c3dtr4e6”中的每个数字字符,然后查找其中每个字母字符,编写两个版本的程序,第一个使用find_first_of,第二个要使用find_first_not_of.

1 int main()
2 {
3     string alphabet{"ab2c3dtr4e6"};
4     string numbers{"0123456789"};
5     while((pos=alphabet.find_first_of(numbers,pos))!=string::npos){
6     cout<<pos<<"is"<<alphabet[pos]<<endl;
7      ++pos;}
8     return 0;
9 }
1 int main()
2 {
3     string alphabet{"ab2c3dtr4e6"};
4     string numbers{"0123456789"};
5     while((pos=alphabet.find_first_not_of(numbers,pos))!=string::npos){
6     cout<<pos<<"is"<<alphabet[pos]<<endl;
7      ++pos;}
8     return 0;
9 }

练习9.48

假定name和numbers的定义如325页所示,number.find(name)返回什么?

返回string::npos;

练习9.49

如果一个字母延伸到中线之上,如d或f,则称其有上出头部分,如果一个字母延伸到中线之下,就是下出头,编写程序,读入一个单词文件,输出最长的既不包含上出头部分,也不包含下出头的单词

 1 #include<iostream>
 2 #include<string>
 3 #include<fstream>
 4  
 5 using std::string;using std::ifstream;using std::endl;using std::cout;
 6  
 7 int main()
 8 {
 9     ifstream ifs("word.txt");
10     if(!ifs)
11         return -1;
12  
13     string longest_word;
14     for(string word; ifs>>word; )
15         if(word.find_first_not_of("aceimnorsuvwxz") == string::npos && 
16                                                word.size()>longest_word.size())
17             longest_word = word;
18     cout<<longest_word<<endl;
19  
20     ifs.close();
21  
22     return 0;
23 }

练习9.50

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

 1 int main()
 2 {
 3     std::vector<string> numbers{"123lkj123lkj123","123hjg","123bgh"};
 4     
 5     
 6 int sum=0;
 7     for(auto d:numbers)
 8     
 9     sum+=stoi(d);
10     cout<<sum<<endl;
11     
12 }
 1 int main()
 2 {
 3     std::vector<string> numbers{"123lkj123lkj123","123hjg","123bgh"};
 4     
 5     
 6 double sum=0;
 7     for(auto d:numbers)
 8     
 9     sum+=stod(d);
10     cout<<sum<<endl;
11     
12 }

练习9.51

设计一个类,它有三个unsigned成员,分别表示年、月、日。为其编写构造函数,接受一个表示日期的string参数。你的构造函数应该能处理不同数据格式。

 

 1 class date{
 2     public:
 3         date(const string &a);
 4         
 5         unsigned year=0,month=0,day=0;    
 6 }; 
 7 
 8 date::date(const string &a)
 9 {string::size_type pos=0;
10     string notion{"/ ,"};
11     if(a[0]>'A'&&a[0]<'z'){
12         
13         if(a.substr(0,2)=="Jan")
14         month=1;
15         else if(a.substr(0,2)=="Feb")
16         month=2;
17         else if(a.substr(0,2)=="Mar")
18         month=3;
19         else if(a.substr(0,2)=="Apr")
20         month=4;
21         else if(a.substr(0,2)=="May")
22         month=5;
23         else if(a.substr(0,2)=="Jun")
24         month=6;
25         else if(a.substr(0,2)=="Jul")
26         month=7;
27         else if(a.substr(0,2)=="Aug")
28         month=8;
29         else if(a.substr(0,2)=="Sep")
30         month=9;
31         else if(a.substr(0,2)=="Oct")
32         month=10;
33         else if(a.substr(0,2)=="Nov")
34         month=11;
35         else if(a.substr(0,2)=="Dec")
36         month=12;
37     pos=a.find_first_of(notion,pos);
38     ++pos;
39     }
40     
41     else 
42     {
43     month=stoi(a);
44     ++pos;
45 }
46 day=stoi(a);
47 ++pos;
48 year=stoi(a);
49     
50 }

练习9.52

使用stack处理括号化的表达式。当你看到一个左括号,将其记录下来,当你在一个左括号之后看到一个右括号,从stack中pop对象,直至遇到左括号,将左括号一起弹出栈。然后将一个值push到栈中

  1 #include <iostream>
  2 #include <vector>
  3 #include <stack>
  4 #include <string>
  5 #include <cstdlib>
  6 #include <cctype>
  7 #include <cstring>
  8 using namespace std;
  9 
 10 vector<string> prepare(char *str)
 11 {
 12     vector<string> tokens;
 13     int len=strlen(str);
 14     char *p=(char*)malloc(sizeof(char)*len+1);
 15     int i=0,j=0;
 16     while(i<len)
 17     {
 18         if(str[i]==' ')
 19         {
 20         ++i;
 21         continue;
 22         }
 23         p[j]=str[i];
 24         ++j;
 25         ++i;
 26     }
 27     p[j]='\0';
 28     j=0;
 29     len=strlen(p);
 30     while(j<len)
 31     {
 32         string token;
 33         char temp[2];
 34         if(p[j]=='('||p[j]==')'||p[j]=='+'||p[j]=='*'||p[j]=='/')
 35         {
 36             temp[0]=p[j];
 37             temp[1]='\0'; 
 38             token=temp;
 39             tokens.push_back(token);
 40             
 41             
 42         }
 43         else if(p[j]=='-')
 44         {
 45             if(p[j-1]==')'||isdigit(p[j-1]))
 46             {
 47                 temp[0]=p[j];
 48                 temp[1]='\0';
 49                 token=temp;
 50                 tokens.push_back(token);
 51             }
 52             else
 53             {
 54                 temp[0]='#';
 55                 temp[1]='\0';
 56                 token=temp;
 57                 tokens.push_back(token);
 58                 
 59             }
 60         
 61 
 62         }
 63         else
 64         {
 65             i=j;
 66             while(isdigit(p[i])&&i<len)
 67             ++i;
 68             char *opd=(char*)malloc(i-j+1);
 69             strncpy(opd,p+j,i-j);
 70             opd[i-j]='\0';
 71             token=opd;
 72             tokens.push_back(token);
 73             j=i-1;
 74             free(opd);
 75             
 76         }
 77         ++j;
 78     }free(p);
 79     return tokens;
 80 }
 81 
 82 int getPriority(string opt)
 83 {
 84     int priority;
 85     if(opt=="#")
 86         priority = 3;  
 87     else if(opt=="*"||opt=="/")
 88         priority = 2;
 89     else if(opt=="+"||opt=="-")
 90         priority = 1;
 91     else if(opt=="(")
 92         priority = 0;
 93     return priority;
 94 }
 95 
 96 void calculate(stack<int> &opdStack,string opt)
 97 {
 98     if(opt=="#")  //进行负号运算
 99     {
100         int opd = opdStack.top();
101         int result = 0-opd;
102         opdStack.pop();
103         opdStack.push(result);
104         cout<<"操作符:"<<opt<<" "<<"操作数:"<<opd<<endl; 
105     }
106     else if(opt=="+")
107     {
108         int rOpd = opdStack.top();
109         opdStack.pop();
110         int lOpd = opdStack.top();
111         opdStack.pop();
112         int result = lOpd + rOpd;
113         opdStack.push(result); 
114          
115         cout<<"操作符:"<<opt<<" "<<"操作数:"<<lOpd<<" "<<rOpd<<endl; 
116     }
117     else if(opt=="-")
118     {
119         int rOpd = opdStack.top();
120         opdStack.pop();
121         int lOpd = opdStack.top();
122         opdStack.pop();
123         int result = lOpd - rOpd;
124         opdStack.push(result); 
125         cout<<"操作符:"<<opt<<" "<<"操作数:"<<lOpd<<" "<<rOpd<<endl; 
126     }
127     else if(opt=="*")
128     {
129         int rOpd = opdStack.top();
130         opdStack.pop();
131         int lOpd = opdStack.top();
132         opdStack.pop();
133         int result = lOpd * rOpd;
134         opdStack.push(result); 
135         cout<<"操作符:"<<opt<<" "<<"操作数:"<<lOpd<<" "<<rOpd<<endl; 
136     }
137     else if(opt=="/")
138     {
139         int rOpd = opdStack.top();
140         opdStack.pop();
141         int lOpd = opdStack.top();
142         opdStack.pop();
143         int result = lOpd / rOpd;
144         opdStack.push(result); 
145         cout<<"操作符:"<<opt<<" "<<"操作数:"<<lOpd<<" "<<rOpd<<endl; 
146     }
147 }
148 
149 int evamidexpr(char *str)
150 {
151     vector<string> tokens=prepare(str);
152     int i=0;
153     int len=tokens.size();
154     stack<int> opdStack;
155     stack<string> optStack;
156     while(i!=len)
157     {
158         string token=tokens[i];
159         if(token=="#"||token=="+"||token=="-"||token=="*"||token=="/")
160         {
161             if(optStack.empty())
162             optStack.push(token);
163             else
164             {
165                 if(getPriority(token)>getPriority(optStack.top()))
166                     optStack.push(token);
167                 else
168             {
169                 int tokenPriority = getPriority(token);
170                 string topOpt = optStack.top();
171                 int topOptPriority = getPriority(topOpt);
172                 if(tokenPriority>topOptPriority)
173                 {
174                     optStack.push(token);
175                 }
176                 else
177                 {
178                     while(tokenPriority<=topOptPriority)
179                     {
180                         optStack.pop();
181                         calculate(opdStack,topOpt);
182                         if(optStack.size()>0)
183                         {
184                             topOpt = optStack.top();
185                             topOptPriority = getPriority(topOpt);
186                         }
187                         else
188                             break;
189                          
190                     }
191                     optStack.push(token);
192                 }
193             }  
194         }}
195         else if(token=="(")
196         {
197             optStack.push(token);
198         }
199         else if(token==")")
200         {
201             while(optStack.top()!="(")
202             {
203                 calculate(opdStack,optStack.top());
204                 optStack.pop();
205             }
206             optStack.pop();
207         }
208         else
209         {
210             opdStack.push(atoi(token.c_str()));
211         }
212         ++i;
213     } while(optStack.size()!=0)
214     {
215         
216         calculate(opdStack,optStack.top());
217         optStack.pop();
218     }
219     return opdStack.top();
220 }
221 
222 
223 
224 
225 
226 
227 
228 
229 int main(int argc, char *argv[])
230 {     char *a = "((3+5*2)+3)/5+(-6)/4*2+3";
231     
232 cout<<evamidexpr(a)<<endl;    
233 return 0;
234 }

 



这篇关于C++primer9.5节练习的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程