!!!C++ Primer 练习题

来源:互联网 发布:阿里云openstack架构 编辑:程序博客网 时间:2024/04/27 23:51

Problem 3.10

Write a program to strip the punctuation from a string. The input to the program should be a string of characters including punctuation; the output should be a string in which the punctuation is removed.

My code:

#include <iostream>#include <string>#include <cctype>using std::string;using std::cin;using std::cout;int main(){string s1;cin >> s1;string::size_type i;for(i=0; i < s1.size(); ++i){if(!ispunct(s1[i]))cout << s1[i];}cout << std::endl;}

Problem 3.13

Read a set of integers into a vector. Calculate and print the sum of each pair of adjacent elements in the vector. If there is an odd number, tell the user and print the value of the last element withou summing it.

my code:

#include <iostream>#include <vector>using std::vector;using std::cin;using std::cout;int main(){  vector<int> inputint;  int tmp, num = 0;  while ( cin >> tmp)                                  //cin can be used to detect if the input is valid  {  inputint.push_back(tmp);  num ++;  }  cout << "The number of int is:" << num << std::endl;  if (num % 2 == 0)  {  for (int i = 0; i < num; i+=2)  cout << (inputint[i] + inputint[i+1]) << std::endl;  }  else  {  for (int i = 0; i < num - 1; i+=2)  cout << (inputint[i] + inputint[i+1]) << std::endl;  cout << inputint[num - 1] << std::endl;  }}

Problem 4.34

Write a program to read strings into a vector. Now, copy that vector into an array of character pointers. For each element in the vector, allocate a new character array and copy the data from the vector element into the character array. Then insert a pointer to the character array into the array of character pointers.

my code:

#include <iostream>#include <String>#include <vector>using std::vector;using std::cin;using std::cout;using std::endl;using std::string;int main(){  string temp;  vector<string> vec_str;  cout << "please begin:" << endl;  while (cin >> temp)  vec_str.push_back(temp);            //vec_str is used to store the input strings  size_t len = vec_str.size();  char **chptr = new char*[len];              //chptr is the char array used to store the pointers  int sub_chptr = 0;                          //sub_chptr is used to count the number of strings, the index of chptr  //create a char array for each string  for(vector<string>::iterator iter = vec_str.begin(); iter != vec_str.end(); ++iter)  {  string temp_iter = *iter;           //use temp_iter to store each string  chptr[sub_chptr] = new char[temp_iter.size()+1];       //allocate space and assign each pointer in chptr  for (string::size_type ix = 0; ix != temp_iter.size(); ix++)  {  chptr[sub_chptr][ix] = temp_iter[ix];  }  chptr[sub_chptr][temp_iter.size()] = '\0';  ++sub_chptr;  }  //output strings  for( int i = 0; i != vec_str.size(); ++i)  {  int j = 0;  while (chptr[i][j] != '\0')  {  cout << chptr[i][j];  ++j;  }  cout << endl;  }}

Problem 5.7

Write the condition for a while loop that would read ints from the standard input and stop when the value read is equal to 42.

while (cin >> ival && ival != 42)

Problem 5.18

Write a program that defines a vector of pointers to strings. Read the vector, printing each string and its corresponding size

#include <iostream>#include <String>#include <vector>using std::vector;using std::cin;using std::cout;using std::endl;using std::string;int main(){  string temp;   string *ptr;  vector<string*> vecstr;  while (cin >> temp)  {  string *tstring = new string;            //How to use new P135  *tstring = temp;  vecstr.push_back(tstring);  }  for (vector<string*>::iterator iter = vecstr.begin(); iter != vecstr.end(); ++iter)  cout << **iter << (**iter).size() <<endl;}

Problem 6.3

Use the comma operator to rewrite the else branch in the while loop from the bookstore problem so that it no longer requires a block.

Original else statement:

else{std::cout << total << std::endl;total = trans;}
Solution:

elsestd::cout << total << std::endl, total = trans;


Usage of comma operator(From msdn):
The comma operator has left-to-right associativity. Two expressions separated by a comma are evaluated left to right. The left operand is always evaluated, and all side effects are completed before the right operand is evaluated.
Commas can be used as separators in some contexts, such as function argument lists. Do not confuse the use of the comma as a separator with its use as an operator; the two uses are completely different.
Consider the expression

e1 , e2
The type and value of the expression are the type and value of e2; the result of evaluating e1 is discarded. The result is an l-value if the right operand is an l-value.
Where the comma is normally used as a separator (for example in actual arguments to functions or aggregate initializers), the comma operator and its operands must be enclosed in parentheses. For example:
func_one( x, y + 2, z );func_two( (x--, y + 2), z );
In the function call to func_one above, three arguments, separated by commas, are passed: x, y + 2, and z. In the function call to func_two, parentheses force the compiler to interpret the first comma as the sequential-evaluation operator. This function call passes two arguments to func_two. The first argument is the result of the sequential-evaluation operation (x--, y + 2), which has the value and type of the expression y + 2; the second argument is z.


Problem 6.9

Modify our vowel-count program so it counts the number of occurrences of the following two-character sequences: ff, fl, and fi.

Original vowel-count program:

char ch;int aCnt = 0, eCnt = 0, iCnt = 0, oCnt = 0, uCnt = 0;while (cin >> ch){  Switch (ch)  {    case 'a':      ++aCnt;      break;    case 'e':      ++eCnt;      break;    case 'i':      ++iCnt;      break;    case 'o':      ++oCnt;      break;    case 'u':      ++uCnt;      break;  }}
Solution:
//Add the following after the switch above:if (oldch == 'f')switch (ch){case 'f':++ffCnt;break;case 'l':++flCnt;break;case 'i':++fiCnt;break;}
Assign ch to oldch after each loop/test of both switches.

Problem 6.12

Write a small program to read a sequence of strings from standard input looking for duplicated words.The program should find places in the input where one word is followed immediately by itself. Keep track of the largest number of times a single repetition occurs and which word is repeated. Print the maximum number of duplicates, or else print a message saying that no word was repeated.

PS: the question only require the code the find the word that immediately follow itself. But my code will calculate whenever the same word repeat.

My code(only show the first word if many words repeat same times):

#include <iostream>#include <String>#include <vector>using std::vector;using std::cin;using std::cout;using std::endl;using std::string;int main(){  string temp;  vector<string> sword;     //store words  vector<int> scount;       //s //read the first word    if (cin >> temp)  {    sword.push_back(temp);      scount.push_back(1);  }  else  cout << "error" << endl;//continue read words  while (cin >> temp)  {  vector<string>::iterator witer=sword.begin();  vector<int>::iterator citer=scount.begin();  while (witer != sword.end() && *witer != temp)  {  ++ witer;  ++ citer;  }  if (witer != sword.end())       //increase scount if find the word    ++(*citer);  else                            //create new word and count  {  sword.push_back(temp);  scount.push_back(1);  }  }//find the word with maximum duplicates  vector<string>::iterator Maxwiter = sword.begin(), witer = sword.begin();  vector<int>::iterator Maxciter = scount.begin(), citer = scount.begin();  for(;witer != sword.end(); ++witer, ++citer)  {  if (*citer > *Maxciter)  {  Maxwiter = witer;  Maxciter = citer;  }  }  if (*Maxciter > 1)      cout << "The word: " << *Maxwiter << " appears " << *Maxciter << " times." << endl;  else  cout << "no word repeated" << endl;}


Problem 7.3

Write a program to take two int parameters and generate the result of raising the first parameter to the power of the second. Write a program to call your function passing it two ints.

Answer(Need to consider when power is 0 or negative):

double powerOf(int i1, int i2) {double d1 = i1;bool negExp = false;if (i2 == 0) // 0 Exponent{return 1;}else if (i2 < 0) // Negative Exponent{negExp = true;i2 = -i2;for ( ; i2 != 1; --i2)d1 *= i1;d1 = 1 / d1;return d1;}else            // Positive Exponent{for ( ; i2 != 1; --i2)d1 *= i1;return d1;}  // We should never get to here.return -1;}int main(){int i1, i2;cin >> i1 >> i2;double d1 = powerOf(i1, i2);return 0;}


Problem 8.3 & 8.4

Write a function that takes and returns an istream&. The function should read the stream until it hits end-of-file. The function should print what it reads to the standard output. Reset the stream so that it is valid and return the stream.

//iosteam header includes istream class and ostream class,//so there is no need to include istream header#include <iostream>#include <String>using std::cin;using std::cout;using std::endl;using std::string;using std::istream;      //istream is a class, like string, we need to define the namespaceistream& rw(istream& is){string s;while(is >> s, !is.eof())       //here is is used like cin{cout << s << endl;}is.clear();return is;}int main(){rw(cin);return 0;}

Problem 8.6

Use the function you wrote for problem 8.3/8.4 to read a named file:

#include <iostream>#include <String>#include <fstream>using std::cin;using std::cout;using std::endl;using std::string;using std::istream;      //istream is a class, like string, we need to define the namespaceusing std::ifstream;istream& rw(istream& is){string s;while(is >> s, !is.eof())       //here is is used like cin{cout << s << endl;}is.clear();return is;}int main(){    ifstream input;input.open("input.txt");        //need to add the surfix to specify the fileif (!input)                     //check error{cout << "error"<< endl;return -1;}rw(input);return 0;}

Problem 8.9

Write a function to open a file for input and read its contents into a vector of strings, storing each line as a separate element in the vector

#include <iostream>#include <String>#include <fstream>#include <vector>using std::cin;using std::cout;using std::endl;using std::string;using std::istream;      using std::ifstream;using std::vector;istream& rw(istream& is, vector<string> &svect)    //pass a vector as a reference{string s, sum;while(getline(is, s))                      //use getline function to get each line{svect.push_back(s);}is.clear();return is;}int main(){    ifstream input;input.open("input.txt");        if (!input){cout << "error"<< endl;return -1;}vector<string> vect;rw(input, vect);for(vector<string>::iterator siter = vect.begin(); siter != vect.end(); ++siter)cout << *siter << endl;cout << vect.size() <<endl;return 0;}

Problem 8.10

Same as 8.9, but store each word as a separate element in the vector

#include <iostream>#include <String>#include <fstream>#include <vector>using std::cin;using std::cout;using std::endl;using std::string;using std::istream;      using std::ifstream;using std::vector;istream& rw(istream& is, vector<string> &svect)      //pass a vector as a reference{string s;while(is >> s, !is.eof())      {svect.push_back(s);}is.clear();return is;}int main(){    ifstream input;input.open("input.txt");        if (!input){cout << "error"<< endl;return -1;}vector<string> vect;rw(input, vect);for(vector<string>::iterator siter = vect.begin(); siter != vect.end(); ++siter)cout << *siter << endl;cout << vect.size() <<endl;return 0;}

Problem 9.26

Using the following definition of ia, copy ia into a vector and into a list. Use the single iterator form of erase to remove the elements with odd values from your list and the even values from your vector.

int ia[] = {0,1,1,2,3,5,8,13,21,55,89};

Answer only include the vector part, but list should be similar(remember to initialize the iterator before use it):

#include<iostream>#include<vector>#include<list>using namespace std;int main(){int ia[]={0,1,1,2,3,5,8,13,21,55,89};vector<int> ib;ib.insert(ib.begin(), ia, ia+sizeof(ia)/sizeof(int));vector<int>::iterator iterb=ib.begin();     //must initializewhile(iterb!=ib.end()){if(*iterb%2==0)iterb=ib.erase(iterb);else++iterb;}for(iterb=ib.begin(); iterb!=ib.end();++iterb)cout << *iterb <<endl;}

Problem 9.30

Write a program to explore the allocation strategy followed by the library you use for vector objects:

#include<iostream>#include<vector>using namespace std;int main(){vector<int> ivec;for (vector<int>::size_type ix = 0; ix != 50; ++ix){ivec.push_back(ix);cout << "ivec: size: " << ivec.size()<< " capacity: " << ivec.capacity() << endl;}}
When the maximum capacity in my implementation is reached, it increments by half of itself. This leads to the sequence, 0, 1, 2, 3, 4, 6, 9, 13, 19, 28, 42, and 63.

Problem 10.19

Define a map for which the key is the family surname and the value is children's name & birthday. Then try to search the surname:

#include<fstream>#include<iostream>#include<vector>#include<utility>#include<String>#include<map>using namespace std;int main(){  ifstream f1;  ofstream f3;  f1.open("f1.txt");  string lastName, firstName, birth;  map<string, map<string, string> > record;  map<string, map<string, string> >::iterator check;  while(f1 >> lastName >> firstName >> birth)  {  check = record.find(lastName);         //check if the family name exist  if(check == record.end())              //if not exist, create a new pair  {    map<string, string> newmap;        //since the second element is map, cannot use make_pair!      check=record.insert(make_pair(lastName, newmap)).first;  //fetch the iterator location of the new element  }      check->second.insert(make_pair(firstName, birth));  //insert the inner map, as we already got the iterator   }  cout << "input the last Name:";  cin >> lastName;  check = record.find(lastName);  if (check == record.end())  cout << "Not found" << endl;  else  {map<string, string>::iterator iter = check->second.begin();while (iter != check->second.end()){cout << lastName << "   " << iter->first << "   " << iter->second << endl;++iter;}  }}
The data I used to test:

wang stu 1987/5/6zhang bu 1958/4/8shen acc 1968/4/7wang acc 1963/4/2zhang tuyou 1964/11/8li  brew  1978/5/6li stu 1856/7/4shen atu 1984/6/8zhang crow 1987/11/12


原创粉丝点击