Give your class a < operator and define a vector of HasPtrs. Give that vector some elements and then sort the vector. Note when swap is called.
#include
using std::string;
#include
#include
using std::vector;
#include
using std::sort;
class Has_ptr
{
friend void swap(Has_ptr &, Has_ptr &);
public:
// constructor with default argument
Has_ptr(const std::string &s = std::string()) :
ps(new std::string(s)), i(0) { }
// copy destructor:
//each Has_ptr has its own copy of the string to which ps points
Has_ptr(const Has_ptr &p) :
ps(new std::string(*p.ps)), i(p.i) { }
// assignment operator
Has_ptr &operator=(const Has_ptr &rhs);
bool Has_ptr::operator<(const Has_ptr &rhs);
// destructor: free the memory allocated in constructor
~Has_ptr() { delete ps; }
private:
std::string *ps;
int i;
};
// assignment operator: can handle self-assignment
Has_ptr &Has_ptr::operator=(const Has_ptr &rhs)
{
string *newp = new string(*rhs.ps); // copy the underlying string
delete ps; // free the old memory
ps = newp; // copy data from rhs into this object
i = rhs.i;
return *this;
}
bool Has_ptr::operator<(const Has_ptr &rhs)
{
return *this->ps < *rhs.ps;
}
bool is_shorter(Has_ptr &lhs, const Has_ptr &rhs)
{
return lhs < rhs;
}
inline void swap(Has_ptr &lhs, Has_ptr &rhs)
{
using std::swap;
swap(lhs.ps, rhs.ps);
swap(lhs.i, rhs.i);
}
int main(void)
{
string arr[] = {"j", "i", "h", "g", "f", "e", "d", "c", "b", "a"};
vector vec;
for (int ix = 0; ix != 10; ++ix)
{
Has_ptr hp(arr[ix]);
vec.push_back(hp);
}
sort(vec.begin(), vec.end(), is_shorter);
return 0;
}