- 论坛徽章:
- 2
|
最近在琢磨algorithm的内部实现方式
std::advance接受一个数字作为Distance,那么我觉得它的内部实现是否应该这样:
- template<class InputIt, class Distance>
- void advance(InputIt& it, Distance n>
- {
- advance_impl(it, n, Iterator_trait<InputIt>::categary)
- }
复制代码 对于random_access的category
- template<class InputIt, class Distance>
- void advance_impl(InputIt& it, Distance n>
- {
- it = it +n
- }
复制代码 对于非random_access的category
- template<class InputIt, class Distance>
- void advance_impl(InputIt& it, Distance n>
- {
- if(n==0)return
- else if(n>0)
- {
- for(Distance d=0;d<n;++d)
- ++it
- }
- else
- {
- for(Distance d=0;d<n;++d)
- --it;
- }
- }
复制代码 上面只是我的想法,实际的std::advance 需要用这样的if/else来实现吗,对于n=0,>0,<0的情况分别处理?
可能我的实现繁琐了。更好的方式是什么样子的?
谢谢 |
|