所用头文件:algorithm,functional
一、泛型算法
1.copy:将一个容器的指定的区间的值拷贝到另一个容器的指定位置
//自己实现的copy泛型算法
template<typename T1,typename T2>
void _My_Copy(const T1& _left, const T1& _right, T2 _position)
{
T1 tmp = _left;
for (; tmp != _right; tmp++)
{
*_position = *tmp;
}
}
int main()
{
vector<int>v1;
for (int i = 10; i > 0; i--)
{
v1.push_back(i);
}
copy(v1.begin(), v1.end(), ostream_iterator<int>(cout, " "));//系统自带的copy
cout << endl;
vector<int> v2;
//copy(v1.begin(), v1.end(), inserter(v2, v2.begin()));
_My_Copy(v1.begin(), v1.end(), inserter(v2, v2.begin()));
_My_Copy(v2.begin(), v2.end(), ostream_iterator<int>(cout, " "));
cout << endl;
return 0;
}
2.find:查找一个容器的某段区间内是否存在某个值,如果有,返回值是迭代器,没有的话,返回的是查找区间的右区间值
//自己实现的find泛型算法
template<typename IT,typename FIND>
IT _My_Find(IT _left, IT _right, FIND find)
{
while (_left != _right)
{
if (*_left == find)
{
return _left;
}
_left++;
}
return _left;
}
int main()
{
vector<int>::iterator it=_My_Find(v1.begin(), v1.end(), 5);//返回值为一个迭代器的位置
//vector<int>::iterator it = find(v1.begin(), v1.end(), 5);
if (it == v1.end())
{
cout << "not find." << endl;
}
else
{
cout << *it << endl;
}
return 0;
}
3.sort:将迭代器某段区间的值排序
4.find_if:在一个容器的区间内找比某一个小的第一个数
IT My_Find_if(IT _left, IT _right, T find)
{
IT _tmp = _left;
while (_tmp != _right)
{
if (find(*_tmp))
{
return _tmp;
}
_tmp++;
}
}
二、函数对象
1.函数对象是什么?
函数对象:修饰词为函数,本质上是对象,是一个类模板实例化后的对象,但是因为重载了(),所以在调用时与调用函数形式相类似,所以叫做函数对象。
2.代码实现与调用
1.greater
template<typename T>
class Mgreater
{
public:
bool operator()(T a, T b)
{
cout << "bool operator()" << endl;
return a > b;
}
};
int main()
{
Mgreater<int> A;
bool tmp = A(30, 20);
cout << "返回值" << tmp << endl;
return 0;
}
2.less
template<typename T>
class Mless
{
public:
typedef T TYPR_SECOND;
typedef T TYPR_FRIST;
typedef bool TYPE_RET;
bool operator()(T a, T b)
{
cout << "bool operator()" << endl;
return a < b;
}
};
3.binder1st:绑定器,第一个参数不变
4.binder2nd:将第二个参数绑定不变
template<typename PRE>
class Mbinder2nd
{
public:
Mbinder2nd(PRE pre, typename PRE::TYPR_SECOND val)
:_pre(pre), _val(val)
{
}
typename PRE::TYPE_RET operator()(typename PRE::TYPR_FRIST tmp)
{
return _pre(tmp, _val);
}
private:
PRE _pre;
typename PRE::TYPR_SECOND _val;
};
int main()
{
vector<int>v1;
for (int i = 10; i > 0; i--)
{
v1.push_back(i);
}
copy(v1.begin(), v1.end(), ostream_iterator<int>(cout, " "));
cout << endl;
vector<int>::iterator it2 = My_Find_if(v1.begin(), v1.end(), Mbinder2nd<Mless<int>>(Mless<int>(),5));//找到第一个比5小的数
if (it2 == v1.end())
{
cout << "没有找到" << endl;
}
else
{
cout << *it2 << endl;
}
return 0;
}