- 原因:STL 中的算法通常比手写循环更高效,手写循环容易出错,STL 算法更加清晰。
- 原则:如果需求和 STL 中的算法相同/类似,而且调用算法非常清晰,则调用算法。如果需要的仅仅是简单的循环,而且使用算法需要引入多个 binders 或 adapters,则手写循环。如果需要在循环中作复杂操作,将操作封装在函数对象中,然后调用算法。
Item 44:用成员函数代替同名的算法。
- 成员函数的算法具有更好的性能,因为他们知道普通算法不知道的信息(具体容器的实现)。
- 成员函数的算法具有更好的正确性,主要表现在相等和等价性的一致上。
Item 45:区分 count, find, binary_search, lower_bound, upper_bound, 和 equal_range。
| What You Want to Know? | Algorithm to Use | Member Function to Use | ||
| On an Unsorted Range | On a Sorted Range | With a set or map | With a multiset or multimap | |
| Does the desired value exist? | find | binary_search | count | find |
| Does the desired value exist? If so, where is the first object? | find | equal_range | find | find or lower_bound |
| Where is the first object with a value not preceding the desired value? | find_if | lower_bound | lower_bound | lower_bound |
| Where is the first object with a value succeeding the desired value? | find_if | upper_bound | upper_bound | upper_bound |
| How many object have the desired value? | count | equal_range, then distance | count | count |
| Where are all the objects with the desired value? | find (iteratively) | equal_range | equal_range | equal_range |
Item 46:用函数对象代替函数作为算法的参数。
- 函数对象在 STL 算法中以模板展开方式运行,可内联,效率高。而函数因为是用函数指针调用,不可内联,所以效率低。
- 函数对象的兼容性也要更好一些。
Item 47:避免编写出不可维护的代码。
- wirte-only code 指 it's easy to write, but it's hard to read and understand。
Item 48:总是包含适当的头文件。
Item 49:学习如何翻译 STL 相关的编译器诊断代码。
Item 50:关注 STL 相关的网站。
- The SGI STL site, http://www.sgi.com/tech/stl
- The STLport site, http://www.stlport.org/
- The Boost site, http://www.boost.org/
- 有趣的容器:slist, rope
本文介绍了使用STL进行高效编程的方法,包括使用算法调用代替手写循环、选择正确的搜索算法、利用成员函数提升性能,以及使用函数对象替代函数等技巧。
1670

被折叠的 条评论
为什么被折叠?



