C++Primer 第9章-顺序容器-课后习题答案 下载本文

内容发布更新时间 : 2024/12/23 9:14:06星期一 下面是文章的全部内容请认真阅读。

37.假设希望一次读取一个字符并写入string对象,而且已知需要读入至少100个字符,考虑应该如何提高程序的性能?

string对象中的字符时连续存储的,为了提高性能,事先应该将对象的容量指定为至少100个字符的容量,以避免多次进行内存的重新分配。可使用 reserve函数实现。

38.已知有如下string对象: “ab2c3d7R4E6”

编写程序寻找该字符串中所有的数字字符,然后再寻找所有的字母字符。以两种版本编写该程序:第一个版本使用find_first_of函数,而第二个版本则使用find_first_not_of函数。 第一个版本:

// 11.15_9.38_find_fist_of.cpp : 定义控制台应用程序的入口点。 //

#include \#include #include

using namespace std;

int _tmain(int argc, _TCHAR* argv[]) {

string strSearchVal( \ ); string numerics(\); string::size_type pos = 0; // find num

while ( ( pos = strSearchVal.find_first_of( numerics, pos )) != string::npos ) { cout << \ \ << pos << \ \ << strSearchVal[pos] << endl; ++pos; }

// find letters

string letters(\); pos = 0;

while ( ( pos = strSearchVal.find_first_of( letters, pos )) != string::npos ) { cout << \ \ << pos << \ << strSearchVal[pos] << endl; ++pos; } system(\);

}

return 0;

第二个版本: #include \#include #include

using namespace std;

int _tmain(int argc, _TCHAR* argv[]) { string strSearchVal( \ ); string numerics(\); string letters(\); string::size_type pos = 0; // find num while ( ( pos = strSearchVal.find_first_not_of( letters, pos )) != string::npos ) { cout << \ \ << pos << \ \ << strSearchVal[pos] << endl; ++pos; } // find letters

}

pos = 0;

while ( ( pos = strSearchVal.find_first_not_of( numerics, pos )) != string::npos ) { cout << \ \ << pos << \ << strSearchVal[pos] << endl; ++pos; }

system(\); return 0;

39.已知有如下string对象:

string line1 = “ We were her pride of 10 she named us:“; string line2 = “Benjamin, Phoenix, the Prodigal“; string line3 = “and perspicacious pacific Suzanne“;

string sentence = line1 + ‘ ‘ + line2 + ‘ ‘ + line3;

编写程序计算sentence中有多少个单词,并指出其中最长和最短单词。如果有多个最长或最短单词,则将它们全部输出。

// 11.15_9.39_find_howManyWords.cpp : 定义控制台应用程序的入口点。 //

#include \#include #include #include

using namespace std;

int _tmain(int argc, _TCHAR* argv[]) { string separators(\); // find how many words string line1 = \; string line2 = \; string line3 = \; string sentence = line1 + ' ' + line2 + ' ' + line3; string word; string::size_type maxLen, minLen, wordLen; vector longestWords, shortestWords; cout << \ << sentence << endl; string::size_type startPos = 0, endPos = 0; size_t cnt = 0; while ( ( startPos = sentence.find_first_not_of( separators, endPos )) != string::npos ) { ++cnt; endPos = sentence.find_first_of( separators, startPos ); if ( endPos == string::npos ) wordLen = sentence.size() - startPos; else wordLen = endPos - startPos; word.assign( sentence.begin() + startPos, sentence.begin() + startPos + wordLen ); startPos = sentence.find_first_not_of( separators, endPos ); if ( cnt == 1 ) { maxLen = minLen = wordLen; longestWords.push_back( word ); shortestWords.push_back( word ); } else { if ( wordLen > maxLen ) {