C++ primer习题笔记第7~9章

1、下面的程序虽然是合法的,但可用性还不够好,指出并改正该程序的局限。

bool test( string& s) { return s.empty();} 

【解答】

其局限在于:此处使用引用形参的唯一目的是避免复制实参,但没有将形参定义为const引用,从而导致不能使用字符串字面值调用该函数(因为非const引用形参只能与完全同类型的非const对象关联)。

可更正为:

bool test ( const string& s) { return s.empty(); }


2、何时应将引用形参定义为const对象?如果在需要const引用时,将形参定义为普通引用,则会出现什么问题?

【解答】

如果使用引用形参的唯一目的是避免复制实参,则应将引用形参定义为const对象。

如果在需要const引用时,将形参定义为普通引用,则会导致不能使用右值和const对象,以及需要进行类型转换的对象来调用该函数,从而不必要地限制了该函数的使用。


3、什么时候应使用指针形参?什么时候应使用引用形参?解释两者的优点和缺点?

【解答】

当函数需要处理数组且函数体不依赖于数组的长度时应使用指针形参,其他情况下应使用引用形参。

指针形参的优点是可以明确地表示函数所操纵的是指向数组元素的指针,而不是数组本身,而且可以使用任意长度的实参数组来调用函数;其缺点是函数体不能依赖于数组的长度,否则容易造成数组内存的越界访问,从而产生错误的结果或导致程序崩溃。

引用形参的优点是在函数体中依赖数组的长度是安全的;其缺点是限制了可以传递的实参数组,只能使用长度匹配的实参数组来调用函数。


4、编写一个主函数main,使用两个值作为实参,并输出它们的和。

【解答】

#include<iostream>

using namespace std;

int main(int argc , char **argv)

{

          //检查命令行参数

           if( argc != 3 ){

                  cout<<"you should use three arguments!"<<endl;

                  return -1;

             }

            //使用标准库函数atof将C风格字符串转换为double型数据

             cout<<"Summation of"<<argv[1]<<" and "<<argv[2]<<" is “<<( atof(argv[1]) + atof(argv[2])) <<endl;

             return 0;

}


5、编写程序使之可以接受main命令行选项,并输出传递给main的实参的值。

【解答】

#include<iostream>

using namespace std;

int main( int argc , char **argv)

{

       cout<<" arguments passed to main():"<<endl;

       for( int i =0;i != argc;++i)

                cout<<argv[i]<<endl;

       return 0;

}


6、list 容器的迭代器不支持关系操作符和算术运算,但一般迭代器支持!=和==运算。


7、使用只带有一个长度参数的 resize 操作对元素类型有什么要求?
【解答】对容器里存放的数据类型必须支持值默认初始化。


8、编写一个程序将一个 list 容器的所有元素赋值给一个 vector 容器,其中 list 容器中存储的是指向 C风格字符串的 char*指针,而 vector 容器的元素则是string 类型。

【解答】

#include  <iostream>
#include  <list>
#include  <vector>
#include  <string>
using  namespace  std;

int main()

{

     char *c_arr[] = {  "one",  "two",  "three" };
     list<char*>  pLst;
     pLst. assign(  c_arr,  c_arr+3 );

     vector<string>  strVec;
     strVec. assign(  pLst. begin(), pLst. end()  );

}


9、解释下面程序实现的功能:
vector<string> svec;
svec.reserve( 1024 );
string text_word;
while ( cin >> text_word )
svec.push_back(  text_word );
svec.resize( svec.size() + svec.size()/2 );
如果该程序读入了 256 个单词,在调整大小后,该容器的容量可能是多少?如果读入 512,或 1000,或 1048 个单词呢?

【解答】

功能:将 svec 的 size 设定为 1024,然后从标准输入设备读入一系列单词,最后将该 vector 对象的大小调整为所读入单词个数的 1.5 倍。
当读入 256 或 512 时,容器的容量不变,仍为 1024,因为容器大小没有超出已分配内存容量。调整大小只改变容器中有效元素的个数,不会改变容量。当读入 1000 时,最后调整容量时,需要 1500 个元素的存储空间,超过了已分配的容量 1024,所以可能重新分配为 1536 的容量。当读入 1048 时,在读入 1025 个时,容器的容量可能会增长为 1536,最后输入完 1048 个单词后,在调整大小后,需要 1572 个元素的存储空间,超过了已分配的 1536,因此再次重分配,容量再增长 0.5倍,变为 2304。


10、对于下列程序任务,采用哪种容器实现最合适?解释选择的理由。

(d)  从一个文件中读入未知数目的整数。对这些整数排序,然后把它们输出到标准输出设备。

【解答】

(d)  如果一边输入一边排序,则采用 list 合适,如果先读入所有的整数,然后排序,则用 vector 合适,因为进行排序最好有随机访问的能力。


11、vector<char> cVec;

string str(  cVec. begin(), cVec. end() );


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

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


13、已知有如下 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 中有多少个单词,并指出其中最长和最短单词。如果有多个最长或最短单词,则将它们全部输出。

【解答】

#include  "stdafx.h"
#include  <iostream>
#include  <vector>
#include  <string>
using  namespace  std;
int main()
{
       string separators(" :\t, \v\r\n\f");
       // find how many words
       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;
       string word;
       string::size_type maxLen, minLen,  wordLen;
       vector<string>  longestWords ,  shortestWords;
       cout  << "\n The sentence is :\n"  << 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  )
                      {
                             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  << "\n\t There are " << cnt << " words in the sentence." << endl;
       vector<string>::iterator  iter;
        // out the longest word
        cout  << "\n\t longest word :"   <<  endl;
        iter = longestWords . begin();
        while  ( iter != longestWords. end()  )
        {
                cout  << *iter++ <<  endl;
        }

        // out the shortest word
        cout  << "\n\t shortest word :"  << endl;
        iter = shortestWords. begin();
        while  ( iter != shortestWords. end()  )
       {
                cout  << *iter++ <<  endl;
       }
       system("pause");
       return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值