Boolan C++ 笔记 七

OOP(Object-Oriented programming) VS. GP(Generic Programming)

  • OOP企图将datas 和 methods 关联在一起
    数据放在类里面,操作这些数据的函数也放在类里面
template<class T,class Alloc = alloc>
class list{
...
void sort();
}

为什么list不能使用::sort() 排序?
先看标准库sort()源码

template<class RandomAccessIterator>
inline void sort(RandomAccessIterator first,RandomAccessIterator last{
if(first!=last){
__introsort_loop(first,last,value_type(first),__lg(last-first)*2);
__final_insertion_sort(first,last);
}
}

template<class RandomAccessIterator,class T,class Size>
void __introsort_loop(RandomAccessIterator first,Random AccessIterator last,
T*,Size depth_limit){
...
RandomAccessIterator cut = __unguarded_partition(first,last,T(__median(*first,*(first+(last-first)/2,*(last-1))));//只有 RandomAccessIterator 才能如此操作
...
}

RandomAccessIterator相关概念
list链表的数据结构导致它提供的迭代器不符合.因为随机访问迭代器 (RandomAccessIterator) 是能在常数时间内移动到指向任何元素的双向迭代器 (BidirectionalIterator) 。而链表的的访问时线性的,不具有跳跃性.因为它得一个个访问下一个.

  • GP却是要将datas 和 methods 分开来

    • Containers和Algorithms 团队可各自闭门造车,其间以Iterator沟通即可.
    • Algorithms通过Iterators 确定操作范围,并通过Iterators取用Containers元素.
    template<class T>
    inline const T& min(const T& a,const T& b){
    return b<a?b:a;
    }

    以上面代码为例,函数 min 不需要知道class T的细节,T只要自己实现好<的操作符重载即可.

tips:所有algorithms,其内最终涉及元素本身的操作,无非就是比大小

template<class T,class Compare>
inline const T& max(const T&a,const T& b,Compare comp){
return comp(a,b)?b:a;
}

bool strLonger(const string& s1,const string& s2){
return s1.size() < s2.size();
}

max(string("zoo"),string("hello"),strLonger);
}

operator overloading

Customizes the C++ operators for operands of user-defined typed.

句法:

Overloaded operators 是具有特殊函数名字的函数

operator op            //(1)
operator type          //(2)
operator new
operator new[]         //(3)
operator delete
operator ddelete[]     //(4)
operator "" suffix-identifier //(5)  since C++11
/*
1) 重载的运算符;
2) 用户定义的转换函数;
3) 分配函数;
4) 解分配函数;
5) 用户定义字面量。
*/

op - 下列 38 个运算符之一:

+ - * / % ˆ & | ~ ! = < > += -= *= /= %= ˆ= &= |= << >> >>= <<= == != <= >= && || ++ -- , ->* -> ( ) [ ]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值