一.
//Ex1_01
//using iterators
//2019年9月28日15:53:10
#include <numeric>
#include <iostream>
#include <iterator>
using namespace std;
int main()
{
double data [] = {2.5,4.5,6.5,5.5,8.6};
std::cout <<"The array contains"<<std::endl;
for(auto iter = std::begin(data);iter != std::end(data);++iter)
std::cout<<*iter<<" ";
std::cout<<std::endl;
auto total = std::accumulate(std::begin(data),std::end(data),0.0);
std::cout<<"The sum of this array is:"<<total<<std::endl;
return 0;
}
//Ex1_02
//using stream iterator
//2019年9月28日16:01:06
#include <numeric>
#include <iostream>
#include <iterator>
using namespace std;
int main()
{
std::cout <<"Enter values separated by space use Ctrl+Z to stop"<<std::endl;
std::cout<< std::accumulate(std::istream_iterator<double>(std::cin),std::istream_iterator<double>(),0.0)<<std::endl;
return 0;
}
//ex1_03
//passing function to an algorithm
//2019年9月28日16:29:23
#include <iostream>
#include <algorithm>
#include <iterator>
#include <functional>
using namespace std;
class Root
{
public:
double operator()(double x){
return sqrt(x);
};
};
int main()
{
double data[] = {1.5,2.5,3.5,4.5,5.5};
//passing a function object
Root root;
cout<<"Square roots of this data:"<<endl;
transform(begin(data),end(data),ostream_iterator<double>(cout," "),root);
cout<<endl;
//using an Lambda expression as an argument
cout<<"Cubes of this data:"<<endl;
transform(begin(data),end(data),ostream_iterator<double>(cout," "),[](double x){return x*x*x;});
cout<<endl;
//using a variable of type std::function<> as argument
function<double(double)> op {[](double x){return x*x;}};
cout<<"Squares of this data:"<<endl;
transform(begin(data),end(data),ostream_iterator<double>(cout," "),op);
cout<<endl;
//using a lambda expression that calls another lambda expression as argument
cout<<"4th powers are:"<<endl;
transform(begin(data),end(data),ostream_iterator<double>(cout," "),[&op](double x){return op(x)*op(x);});
cout<<endl;
return 0;
}