GURU Of THE WEEK Terms 03: Using Standard Library

zhaozj2021-02-08  461

Gotw # 03 Using The Standard Library (OR, TempoRies Revis)

Author: Herb Sutter

Translation: Kingofark

[Declaration]: This article takes the Guru of The Week column on www.gotw.ca website, and its copyright belongs to the original person. Translator Kingofark translated this article without the consent of the original person. This translation is only for self-study and reference, please read this article, do not reprint, spread this translation; people download this translation content, please delete its backup immediately after reading. Translator Kingofark is not responsible for people who violate the above two principles. This declaration.

Revision 1.0

GURU Of The Week Terms 03: Using standard libraries (or talking, interim objects)

Difficulty: 3/10

(The algorithm using the standard library is much better than the algorithm written by yourself. Here we will reuse the example in GOTW Terms 02, with explanation, through simple reuse (Reuse), existing things in those standard libraries Will avoid how much trouble questions.)

[problem]

Once the programmer uses the standard library algorithm rather than writing its own algorithm version, you can first avoid how many flaws in GOTW Terms 02? (Note: As the last time, you cannot change the semantics of the function, even if you do this, you can improve the function itself.)

[Version refurbishment]:

Original error versions:

String Findaddr (List L, String Name)

{

For (List :: item i = l.begin ();

I! = l.end ();

i )

{

IF (* i == name)

{

Return (* i) .addr;

}

}

""; "

}

Corrected version (still there is excessive call to L.End ():

String Findaddr (Const List & L,

Const string & name)

{

String addr;

For (list :: const_iterator i = l.begin ();

I! = l.end ();

i)

{

IF ((* i) .Name == name)

{

AddR = (* i) .addr;

Break;

}

}

Return addr;

}

[answer]

Don't need any other changes, as long as you use Find () to avoid the efficiency of almost all L.End () in the original version of the original version:

String Findaddr (List L, String Name)

{

List :: item I =

Find (l.begin (), l.end (), name);

IF (* i! = l.end ())

{

Return (* i) .addr;

}

""; "

}

Other other modifications are made:

String Findaddr (Const List & L,

Const string & name)

{

String addr;

List :: Const_Iterator i = Find (L.Begin (), L.End (), Name);

IF (i! = l.end ())

{

AddR = (* i) .addr;

}

Return addr;

}

[Learning Guidance]: Please read the algorithm of the standard library, not to write its own algorithm version. This is faster, it's easier, safer!

转载请注明原文地址:https://www.9cbs.com/read-341.html

New Post(0)