My professor likes to use the swap function when sorting. It does the job with less code, but I never see this method being used when I look up sorting functions online.
My professor likes to use the swap function when sorting.
That's excellent. It hints that your professor isn't stuck in the early 90's way of doing things. And you shouldn't be, either.
It does the job with less code, but I never see this method being used when I look up sorting functions online.
Maybe those tutorials were written in C instead of C++.
Maybe they were written by C++ beginners who didn't know they were reinventing the wheel.
So to answer your question...
Is it a good idea to use the "swap" function?
Absolutely.
If anything, it should serve as an incentive to research the C++ standard library further, so that you use more and more of it, becoming a better C++ programmer.
> My professor likes to use the swap function when sorting.
> It does the job with less code
It also does the job in the most efficient way possible.
The standard library already has several overloads of std::swap() customized for efficient swapping of objects belonging to different types used by the library.
In addition, std::swap() is one of those standard functions for which specializations / overloads for user-defined types are expressly permitted by the standard.
Say, we have a swappable class sprite provided by some third party library. To swap two sprites in the most efficient manner possible (without violating its encapsulation), we can confidently write std::swap( sprite_one, sprite_two ) ;.
Subject to the obvious assumption that the people who wrote sprite as a swappable type knew what they were doing - if the general std::swap() is not the most efficient way of swapping sprites, an overload of std::swap() would have been provided by the implementer of the class.