数据结构与算法分析 感悟

#include<iostream>
#include<string>
#include<vector>
#include<iterator>
#include<algorithm>
using namespace std;


const int & findMax(const vector<int> &vec)
{
	size_t max=0;
	for(size_t i=1;i!=vec.size();i++)
	{
		if(vec[i]>vec[max])
			max=i;
	}
	return vec[max];
}


/*错误的版本,使用局部变量作为返回值,这取决于编译器释放maxValue所使用的内存的速度。*/
const int& findMaxError(const vector<int> &vec)
{
	string::value_type maxValue=vec[0];
	for(size_t i=1;i!=vec.size();i++)
		if(vec[i]>maxValue)
			maxValue=vec[i];
	return maxValue;
}
int main(){
	istream_iterator<int> in(cin),eof;
	vector<int> vec(in,eof);
	ostream_iterator<int> out(cout," ");
	copy(vec.begin(),vec.end(),out);
	cout<<endl;
	cout<<findMax(vec)<<endl;

	cout<<findMaxError(vec)<<endl;
	return 0;
}

/*浅拷贝vs深拷贝*/
/*浅拷贝:只拷指针值,不拷贝指针所指对象的值*/
/*当类包含指针数据成员时,默认的拷贝,赋值与析构,都只是操作指针值,
不操作指针所指的对象,只是浅拷贝,造成多个指针指向相同的值*/
#include<iostream>
using namespace std;

class IntCell{
public:
	explicit IntCell(int i=0);
	int read()const;
	void write(int x);
	IntCell(const IntCell &);
	const IntCell &operator=(const IntCell &);
	~IntCell();
private:
	int *storeValue;
};


IntCell::IntCell(int i)
{
	storeValue=new int(i);
}

int IntCell::read()const
{
	return *storeValue;
}

void IntCell::write(int x)
{
	*storeValue=x;
}

IntCell::IntCell(const IntCell &rhs)
{
	storeValue=new int(*rhs.storeValue);
}

/*赋值函数,是左右值都已构造完成,只需要赋值即可*/
const IntCell & IntCell::operator =(const IntCell &rhs)
{
	if(this!=&rhs)
		*storeValue=*rhs.storeValue;
	return *this;
}

IntCell::~IntCell()
{
	delete storeValue;
}


int main(){
	IntCell a(2);
	IntCell b=a;/*拷贝*/
	IntCell c;

	c=b;/*赋值*/
	a.write(4);
	/*浅拷贝时,输出值为4,4,4*/
	/*深拷贝时,输出值为4,2,2*/
	cout<<a.read()<<endl<<b.read()<<endl<<c.read()<<endl;

	return 0;
}

#ifndef WEIWEI_H
#define WEIWEI_H

#include<string>
#include<vector>
#include<functional>
using std::string;
using std::vector;

template <typename object>
const object & findMax(const vector<object> &vec)
{
	return findMax(vec,less<object>());
}

template <typename object,typename comparator>
const object & findMax(const vector<object> &vec,comparator isLessThan)
{
	size_t max=0;
	for(size_t i=1;i!=vec.size();i++)
		if(isLessThan(vec[max],vec[i]))
			max=i;
	return vec[max];

}


class CaseInsensitiveCompare{
public:
	bool operator()(const string &lhs,const string &rhs)const
	{
		return _stricmp(lhs.c_str(),rhs.c_str())<0;
	}
};



#endif

#include"weiwei.h"
#include<iostream>
#include<string>
using namespace std;

int main(){
	vector<string> arr(3);
	arr[0]="Zee";
	arr[1]="alligator";
	arr[2]="crocodile";
	cout<<findMax(arr,CaseInsensitiveCompare())<<endl;
	cout<<findMax(arr)<<endl;
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值