Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't the sort algorithm on this code invoke the class's version of swap?

I've described a swap function in my class and from what I understand if a class defines it's own swap function then it should take precedence over the inbuilt swap function.

The following two lines are from C++ primer and a question follows asking you to use the sort algorithm from the algorithm header on your class and observe how many times swap is called.

"If a class defines its own swap, then the algorithm uses that class-specific version. Otherwise, it uses the swap function defined by the library."

class HasPtr{
public:
    friend void swap(HasPtr&, HasPtr&);
    friend bool operator<(const HasPtr&,const HasPtr&);
    HasPtr(const std::string& s=std::string()) : ps(new std::string(s)), i(0){}
private:
    std::string *ps;
    int i;
};
inline void swap(HasPtr&lhs, HasPtr& rhs){
    using std::swap;
    swap(lhs.ps,rhs.ps);
    swap(lhs.i, rhs.i);
    std::cout<<"Swap was called"<<std::endl;
}
bool operator<(const HasPtr& lhs,const HasPtr& rhs){
    return *lhs.ps<*rhs.ps;
}
int main(){
    std::vector<HasPtr>v1{HasPtr("this"),HasPtr("is"),HasPtr("a"),HasPtr("keyboard")};
    std::sort(v1.begin(),v1.end());}

Now since a call to sort uses < to rearrange the elements and according to the excerpt the algorithm should use the class defined version of swap so "swap was called" should have been printed everytime the algorithm rearranges elements but it seems to not and simply appears to use the default version of swap being std::swap.

like image 747
abhinavmidha96 Avatar asked Sep 16 '19 12:09

abhinavmidha96


1 Answers

std::sort is not required to sort the elements by swapping them. If it does, then it will use the correct version of swap, but it can choose to use other methods. For example, it can call std::rotate, which moves ranges of elements.

like image 126
L. F. Avatar answered Oct 28 '22 05:10

L. F.