最好的代码是什么样的代码?有人说是最短的,有人说是效率最高的.你问我?还是用事实来说话好一点.
事实一: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;
}
}
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;
}
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!”,我不知道你是不是权威的压迫下说出这样的话,如果没有,那我的恭喜你的鉴赏力.
我在这里不断的警告我自己,能让人看懂的代码才是最好的代码.这才是我们写代码的目的.其他都是形式主义的玩弄者.