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

}

}

maxLen = wordLen; longestWords.clear(); longestWords.push_back( word ); }

else if ( wordLen == maxLen ) { longestWords.push_back( word ); }

if ( wordLen < minLen ) { minLen = wordLen; shortestWords.clear(); shortestWords.push_back( word ); }

else if ( wordLen == minLen ) { shortestWords.push_back(word); }

// cout number of words

cout << \ << cnt << \ << endl; vector::iterator iter; // out the longest word

cout << \ << endl; iter = longestWords.begin();

while ( iter != longestWords.end() ) { cout << *iter++ << endl; }

// out the shortest word

cout << \ << endl; iter = shortestWords.begin();

while ( iter != shortestWords.end() ) { cout << *iter++ << endl; }

system(\); return 0;

}

40.编写程序接受下列两个string对象:

string q1( “ When lilacs last in the dooryard bloom’d”); string q2(“The child is father of the man”);

然后使用assign和append操作,创建string对象: string sentence(“The child is in the dooryard”);

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

#include \#include #include using namespace std;

int _tmain(int argc, _TCHAR* argv[]) { string q1( \ ); string q2( \ ); // compare q1 and q2 if ( q1.compare( q2 ) > 0 ) cout << \ << endl; else if ( q1.compare( q2 ) < 0 ) cout << \ << endl; else if ( q1.compare( q2 ) == 0 ) { cout << \ << endl; } // create sentence: string sentence(“The child is in the dooryard”);

}

string sentence;

sentence.assign( q2.begin(), q2.begin() + 12 ); sentence.append( q1, 16, 16);

cout << \ << sentence << endl; system(\); return 0;

41.已知有如下string对象: string generic1(“Dear Ms Daisy:”); string generic2(“MrsMsMissPeople”); 编写程序实现下面函数:

string greet( string form, string lastname, string title, string::size_type pos, int length );

该函数使用replace操作实现以下功能:对于字符串form,将其中的Daisy替换为lastname,将其中的Ms替换为字符串generic2中从pos下标开始的length个字符。 例如,下面的语句:

string lastName( “ AnnaP” );

string salute = greet( generic1, lastName, generic2, 5, 4 ); 将返回字符串: Dear Miss AnnaP:

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

#include \#include #include using namespace std;

string greet( string form, string lastname, string title, string::size_type pos, int length ) { string::size_type pos_Daisy, pos_Ms; // replace \ while ( ( pos_Daisy = form.find( \) ) != string::npos ) form.replace( pos_Daisy, lastname.size(), lastname );

// replace \ while ( ( pos_Ms = form.find( \) ) != string::npos ) form.replace( pos_Ms, 2, title, pos, length ); return form; }

int _tmain(int argc, _TCHAR* argv[]) { string generic1(\); string generic2(\); string lastName( \); string salute = greet( generic1, lastName, generic2, 5, 4 ); cout << salute << endl; system(\); return 0; }

42.编写程序读入一系列单词,并将它们存储在stack对象中。

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

#include \#include #include #include #include using namespace std;

int _tmain(int argc, _TCHAR* argv[]) { stack strStack; cout << \; string word; while ( cin >> word ) strStack.push( word );

联系客服:779662525#qq.com(#替换为@) 苏ICP备20003344号-4