Your problem has nothing to do with using namespace std;
. The problem is that you're passing an lvalue reference to an int (int&
) to a function that's overloaded on int&
and int*
. If you removed the using directive, you would not be calling your own swap; in fact, your code wouldn't compile, since C++ does not allow implicit conversion from pointers to int. In order to use your function, you would have to call it as swap(&array[1], &array[4]);
Now, if you corrected your function call to reflect this, it should work, regardless of the presence of the using directive. I would, however, advise against doing so; the semantics of std::swap
are to swap two references, not pointers. Not only is overloading standard functions with incompatible semantics confusing to those familiar with the standard library, it may very well break perfectly valid code that uses std::swap
on int*
.
You may be thinking, "But that will only happen if they're using namespace std;
, which they should never do." Believe it or not, however, swap
is exactly the sort of application where you do want that using directive (properly scoped, of course). The reason for this is that user code may do exactly what you're trying to do: specialize the swap
algorithm. If some library code simply said std::swap
, any user-defined overload would be ignored, making that overload useless. If, instead, your code looked like
template <typename T>
void foo (T& a, T& b)
{
using std::swap; // Or simply namespace std;
// ...
swap (a, b);
// ...
}
the compiler would be able to employ ADL correctly and choose user-defined swap for any given T (say, int
), while still being able to use std::swap
for other T.
In other words: always give swap
reference parameters, and use a scoped using declaration whenever you need to swap templated types.
endl
when you mean'\n'
. They are practically equivalent, but the use of the former can slow your program dramatically. – Cleavesendl
will flush the buffer, whereas\n
will fill the buffer first. when writing a lot of stuff, you notice the difference. – Invaginationstd::endl
will go slower. – Cleavesint i = 42; swap(&i, &i);
will seti
to 0, which is wrong. The funny xor trick can be used for stupid interviews, maybe. It has absolutely no value in the real world. – Geri