C++ articles:Guru of the Week #3:使用标准库

    技术2022-05-11  183

    作者:Hub Sutter译者:plpliuly

    /*此文是译者出于自娱翻译的GotW(Guru of the Week)系列文章第3篇,原文的版权是属于Hub Sutter(著名的C++专家,"Exceptional C++"的作者)。此文的翻

    译没有征得原作者的同意,只供学习讨论。——译者*/

    #3 使用标准库难度:3/10

    使用标准库提供的算法比你自己手工写一个要方便的多。仍然以GotW #2中讨论的函数定义为例子,我们将看到如果直接使用标准库将会避免很多问题。

    问题:    如果我们用标准库中的已有算法代替GotW#2中的最初代码中的循环,有哪些问题可以自然避免?(注意:与以前一样,不能改变函数的语义。)

    GotW #2中的问题回顾:    最初的实现:  string FindAddr( list<Employee> l, string name )  {    for( list<Employee>::iterator i = l.begin();         i != l.end();         i++ )    {      if( *i == name )      {        return (*i).addr;      }    }    return "";  }

       经过修改后,除了l.end()依然是每次循环到要调用,其余的不足之处均已修改(译者:请参看GotW #2):   string FindAddr( const list<Employee>& l,                   const string& name )  {    string addr;    for( list<Employee>::const_iterator i = l.begin();         i != l.end();         ++i )    {      if( (*i).name == name )      {        addr = (*i).addr;        break;      }    }    return addr;  }

    答案:    在最初的代码基础上,仅仅用find()代替循环而不做任何其他的修改就可以避免两个不必要临时对象而且可以几乎把初始代码中的对l.end()的冗余调用全部

    去掉:    string FindAddr( list<Employee> l, string name )  {    list<Employee>::iterator i =      find( l.begin(), l.end(), name );

        if( *i != l.end() )    {      return (*i).addr;    }    return "";  }   再结合我们在GotW #2中提到的修改方法,最终可以得到如下代码:   string FindAddr( const list<Employee>& l,                   const string& name )  {    string addr;    list<Employee>::const_iterator i =      find( l.begin(), l.end(), name );

        if( i != l.end() )    {      addr = (*i).addr;    }    return addr;  }  [忠告]尽量使用标准库算法,因为那样比自己手动重新写一个算法要快捷,而且不易出错。(结束)

     


    最新回复(0)