>> When I first compile this new code, there weren't the "#include <algorithm>" and "using
>> std::sort" there, but the compile and the run were still successful. How?
It really shouldn't have, but the only reason I can think of is "compiler forgiveness." The compiler may include a bunch of headers on its own when you build your executable. It's also likely that the compiler looked up sort because it was passed arguments located in the std namespace. In this case, since the iterators returned by begin() and end() were std iterators, the compiler looked in the std namespace for a sort function and used it. One of the names for this is Koenig lookup.
Well that's my best guess anyway. If your compiler had been switched to "picky" mode, it would have thrown up a diagnostic.
>> if int x = 1, what's the difference between x++ and ++x?
The book is right. However, the difference only really matters if you are depending on the return value of the increment, or copying x is performance expensive. Most of the time, neither of these are the case, but when you learn about iterators it should make more sense. You can also write some algorithms that depend on how you increment x, such as a partition:
Code:
int jsw_partition ( int a[], int first, int last )
{
int pivot = first;
while ( first < last ) {
if ( a[first] <= a[last] )
jsw_swap ( &a[pivot++], &a[first] );
++first;
}
jsw_swap ( &a[pivot], &a[last] );
return pivot;
}
>> Why is using "using namespace std" not advisable?
Because it dumps a lot of common class names and common function names into the global namespace, which may cause ambiguity.
Code:
#include <algorithm>
using namespace std;
namespace my
{
template <typename T>
void
sort( fancy_container<T>::iterator begin, fancy_container<T>::iterator end );
}
sort( b, e );
Which sort is the one that should be called here? The standard one, or the one that is specialized for fancy_containers? The argument types are identical. I don't find a bunch of "using std::this" or "using std::that" at the beginning of a file much better though. I wrote a different main.