c++_primer_exercise_1331

本文介绍了一个包含Has_Ptr类定义的C++程序示例。该类实现了一个包含字符串指针和整数的数据结构,并重载了赋值运算符。通过自定义比较函数is_shorter,实现了基于字符串长度对Has_Ptr对象的向量进行排序的功能。此外,还展示了如何使用swap函数交换两个Has_Ptr对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值