C++ Coding style
-
Hi guys, here is a question from a C++ programming course. We have to implement the BubbleSort algorithm over a STL list. As we know, STL lists haven´t got random access iterators, so we can only increment and decrement the iterators (we can´t use expressions such as "i = i-1"). What implementation is better? a) Using an additional function to get the iterator pointing to the previuos element:
template inline T Prev(const T& i) { T j = i; return --j } template void Bubble(T Begin, T End) { for(T i = Begin, i != End, i++) { for(T j = Prev(End); j!=i; j--) { if(*j < *(Prev(j)) swap(*j, *(Prev(j))); } } }
b) Do not use any adittional function, and just use "temporal" stack variables. Guess the implementation ;P I say that "a" is better, my taecher and my best friend think that "b" is better. What do you think? Thanks. "When I look into your eyes, there´s nothing there to see, nothing but my own mistakes staring back at me" -
Hi guys, here is a question from a C++ programming course. We have to implement the BubbleSort algorithm over a STL list. As we know, STL lists haven´t got random access iterators, so we can only increment and decrement the iterators (we can´t use expressions such as "i = i-1"). What implementation is better? a) Using an additional function to get the iterator pointing to the previuos element:
template inline T Prev(const T& i) { T j = i; return --j } template void Bubble(T Begin, T End) { for(T i = Begin, i != End, i++) { for(T j = Prev(End); j!=i; j--) { if(*j < *(Prev(j)) swap(*j, *(Prev(j))); } } }
b) Do not use any adittional function, and just use "temporal" stack variables. Guess the implementation ;P I say that "a" is better, my taecher and my best friend think that "b" is better. What do you think? Thanks. "When I look into your eyes, there´s nothing there to see, nothing but my own mistakes staring back at me"Benchmark it. And realize that you're arguing about a bubble sort! Who cares how you implement it?
-
Benchmark it. And realize that you're arguing about a bubble sort! Who cares how you implement it?
-
The question is not about the algorithm, is about correct implementation. Thanks anyway.
Anonymous wrote: is about correct implementation. There's no such thing--if it works. (Except in this case there may be implementation that will get you an 'A' and implementation that won't.)