C ++ Articles: Guru of The Week # 3: Use a standard library

zhaozj2021-02-08  284

Author: Hub Sutter Translator: plpliuly

/ * This article is a GotW (GURU of the Week) series of self-entertainment translations, the original copyright is the author of Hub Sutter (the famous C expert, "Exceptional C " author). This article

The translation did not produce the consent of the original author, only for learning discussion. - Translator * /

# 3 Use standard library difficulty: 3/10

The algorithm that uses the standard library is more convenient than yourself. Still defined as an example in the function discussed in GOTW # 2, we will see that if you use the standard library directly, you will avoid a lot of problems.

Problem: If we use the existing algorithm in the standard library instead of the cycle in the original code in GOTW # 2, what questions can be naturally avoided? (Note: The semantics of the function cannot be changed as before.)

Problem Review: String Findaddr (List :: Iterator i = L.BEGIN (); iTerator i = L.BEGIN (); i! = L.end () ; I ) {if (* i == Name) {return (* i) .addr;}} return ";

After modification, except for L.End () is still revised every time it is called, the rest of the shortcomings has been modified (Translator: please see GotW # 2): 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;}} returnadr;}

Answer: Based on the initial code, only use of Find () instead of the loop without any other modification, you can avoid the two unnecessary temporary objects and can almost call the redundancy of L.End () in the initial code. All

Remove: String Findaddr (List L, String Name) {List :: Iterator i = Find (L.BEGIN (), L.End (), Name);

IF (* i! = L.End ()) {return (* i) .addr;} return ";} Combined with our modification method mentioned in GOTW # 2, you can finally get the following code: 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;} [Advice] Try to use the standard library algorithm as much as possible, because it is more frequent than yourself, and it is not easy to go wrong. (End)

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

New Post(0)