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