巧用标准c++中的算法函数,对数组进行操作
2006-07-05 11:42
405 查看
我们在c/c++中常用的指针也是算子,它符合算子的所有特性,所以我们可以用c++标准模板库中的algorithm算法函数,来对数组进行操作。这种操作,对于简化程序是十分有帮助的,下面我简单使用程序演示一下如何使用他们,希望能够给网友提供一种思路和一些启发。
#include <iostream>
#include <algorithm>
#include <functional>
using namespace std;
template <typename T>
struct SVisit: public unary_function<T, void>
{
inline void operator()( const T& t ) const
{
cout << t << endl;
}
};
template <typename T>
struct SEqualer: public binary_function<T, T, bool>
{
inline bool operator()( const T& t, const T& value ) const
{
return t == value;
}
};
int main( void )
{
int arr[] = { 2, 5, 6, 9, 1, 0, 4, 6 };
int len = sizeof( arr ) / sizeof( int );
cout << "arr's size = " << len << endl;
for_each( arr, arr + len, SVisit<int>() );
cout << "Replace 6 by 10" << endl;
typedef SEqualer<int> SIntReplacer;
replace_if( arr, arr + len, binder2nd<SIntReplacer>( SIntReplacer(), 6 ), 10 );
for_each( arr, arr + len, SVisit<int>() );
cout << "Delete value = 10" << endl;
typedef SEqualer<int> SIntDeleter;
len = remove_if( arr, arr + len, binder2nd<SIntDeleter>( SIntDeleter(), 10 ) ) - arr;
for_each( arr, arr + len, SVisit<int>() );
return 0;
}
#include <iostream>
#include <algorithm>
#include <functional>
using namespace std;
template <typename T>
struct SVisit: public unary_function<T, void>
{
inline void operator()( const T& t ) const
{
cout << t << endl;
}
};
template <typename T>
struct SEqualer: public binary_function<T, T, bool>
{
inline bool operator()( const T& t, const T& value ) const
{
return t == value;
}
};
int main( void )
{
int arr[] = { 2, 5, 6, 9, 1, 0, 4, 6 };
int len = sizeof( arr ) / sizeof( int );
cout << "arr's size = " << len << endl;
for_each( arr, arr + len, SVisit<int>() );
cout << "Replace 6 by 10" << endl;
typedef SEqualer<int> SIntReplacer;
replace_if( arr, arr + len, binder2nd<SIntReplacer>( SIntReplacer(), 6 ), 10 );
for_each( arr, arr + len, SVisit<int>() );
cout << "Delete value = 10" << endl;
typedef SEqualer<int> SIntDeleter;
len = remove_if( arr, arr + len, binder2nd<SIntDeleter>( SIntDeleter(), 10 ) ) - arr;
for_each( arr, arr + len, SVisit<int>() );
return 0;
}
相关文章推荐
- 对数组进行排序、求最大值和求元素和的算法都编写为函数模板,采用相关数据进行测试。
- 利用函数调用,对数组进行初始化,更改,清零,逆置等操作
- java类中用类的数组作为函数参数传给类,为什么不能直接对类的数组进行操作?
- C#使用自定义算法对数组进行反转操作的方法
- 利用函数调用,对数组进行初始化,更改,清零,逆置等操作
- 数组左旋转k位 —— C++标准算法库中最悲剧的函数:rotate
- 6.对数组进行排序、求最大值和求元素和的函数采用静态成员函数的方式封装成数组算法类模板ArrayAlg,并采用相关数据进行测试。
- 利用函数调用,对数组进行初始化,更改,清零,逆置等操作
- 用json传过来的数组并不是标准的array,所以需要用这个函数进行转换。
- 函数:使用数组名作为函数参数进行操作
- 对数组进行排序、求最大值和求元素和的算法都编写为函数模板,采用相关数据进行测试。
- sort函数的用法(C++排序库函数的调用) 对数组进行排序,在c++中有库函数帮我们实现,这们就不需要我们自己来编程进行排序了。 (一)为什么要用c++标准库里的排序函数 Sort()函数是c+
- 对数组进行排序、求最大值和求元素和的算法都编写为函数模板,采用相关数据进行测试
- 数组左旋转k位 —— C++标准算法库中最悲剧的函数:rotate
- 函数:数组作为函数参数进行操作
- 关于使用定义函数来实现对于数组c中的元素进行筛选最大值最小值,计算平均值等操作
- 数组左旋转k位 —— C++标准算法库中最悲剧的函数:rotate
- 利用函数调用,对数组进行初始化,更改,清零,逆置等操作
- PHP中对数组进行操作的常用函数总结
- windows下对目录进行的操作函数总结