C++ Primer 练习13.3

#include<iostream>
#include<vector>
#include<string>
#include<algorithm>

using namespace std;

static int n = 0;

class HasPtr {
	friend void swap(HasPtr&, HasPtr&);
	friend bool operator<(HasPtr& lhs, HasPtr& rhs);
public:
	HasPtr(const string& s = string()) :
		ps(new string(s)), i(0) {}
	HasPtr(const HasPtr& p) :
		ps(new string(*p.ps)), i(p.i) {}
	HasPtr& operator=(HasPtr rhs) {
		swap(*this, rhs);
		return *this;
	}
	void print() { cout << *ps << endl; }
	~HasPtr() { delete ps; }
private:
	string* ps;
	int i;
};

inline
void swap(HasPtr& lhs, HasPtr& rhs) {
	using std::swap;
	swap(lhs.ps, rhs.ps);
	swap(lhs.i, rhs.i);
	n++;
	cout << "swap" << endl;
}

bool operator<(HasPtr& lhs, HasPtr& rhs) {
	return *lhs.ps < *rhs.ps;
}

int main()
{
	vector<HasPtr> vec{ (string)"sfdd" };
	for (int i = 0; i < 1000; ++i)
		vec.push_back(string("dzx"));
	std::sort(vec.begin(), vec.end());
	cout << n << endl;
	//for (auto m : vec)
	//	m.print();
	return 0;
}

元素数目过少时sort使用插入排序,未使用swap,在VS中临界值似乎为32。
当元素数目变大时,sort会使用快速排序,此时使用自定义版本的swap,当剩余无序元素小于临界值后继续使用插入排序。

注意添加元素时不能让所有元素全部相等,不然编译器就不会使用快速排序,也就不会调用swap。(坑了我好久…)

猜你喜欢

转载自blog.csdn.net/Dzx1025/article/details/107478235