写最好的代码

 最好的代码是什么样的代码?有人说是最短的,有人说是效率最高的.你问我?还是用事实来说话好一点.

事实一:Bjarne Stroustrup(Creator and implementor  of C++ Language)先生的语录:

Remember, a primary aim of writing code is to make its meaning clear to the next person reading it – and that
person just might be yourself a few years hence.

事实二:sgi stl代码:

下面是关于partition这个函数的实现:

template  < class  BidirectionalIterator,  class  Predicate >
BidirectionalIterator partition(BidirectionalIterator first,
                                BidirectionalIterator last, Predicate pred) 
{
  
while (true{
    
while (true)
      
if (first == last)
        
return first;
      
else if (pred(*first))
        
++first;
      
else
        
break;
    
--last;
    
while (true)
      
if (first == last)
        
return first;
      
else if (!pred(*last))
        
--last;
      
else
        
break;
    iter_swap(first, last);
    
++first;
  }

}

以下是我写的一个版本:

int  partition( int *  arr,  int  len)  {
    
int front, back;
    front 
= 0;
    back 
= len - 1;
    
int pivot = arr[(int)(double(rand()) / RAND_MAX)*5];
    
while ( front < back ) {
        
while ( arr[front] < pivot ) 
            
++ front;
        
while ( arr[back] > pivot ) 
            
-- back;
        
if ( arr[front] != arr[back] )
            swap ( arr[front], arr[back] );
        
else {
            
++ front;
            
-- back;
        }

    }

    
    
return back;
}

 你觉得那个好了?可能你会毫不思索的说“sgi stl is best!”,我不知道你是不是权威的压迫下说出这样的话,如果没有,那我的恭喜你的鉴赏力.

我在这里不断的警告我自己,能让人看懂的代码才是最好的代码.这才是我们写代码的目的.其他都是形式主义的玩弄者.

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值