Effective STL 读书笔记 9

Item 43:用算法调用代替手写循环。
  • 原因: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 相关的网站。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值