算法七十三、istream_iterator 科普
#include<iostream>
#include<cstring>
#include<algorithm>
#include<numeric>//accumulate所在库
#include<iterator>//istream_iterator所在库
using namespace std;
int main(){
istream_iterator<int>n(cin),eof;
cout<<accumulate(in,eof,0)<<endl;
return 0;
}
map<string,string>前置定义;
前置定义.insert(make_pair("\EOF","end of file"));
讲解开始!
istream_iterator
-
istream_iterator
,用来从input steam
读取数据。对,cin
也用input steam
读数据。
-
- 例子:
#include<iostream>
#include<iterator>
using namespace std;
int main(){
istream_iterator<int>input(cin);//从input steam读取int数据的迭代器
istream_iterator<int>inteof;//int数据的EOF
while(input!=inteof){
cout<<*input;//输出输入的内容
endl(cout);//换行
++input;//继续读入
}
return 0;
}
input:{
1 2 3 4 5 /EOF
}
output:{
1 2 3 4 5
}
-
- 所以,
cout<<accumulate(in,eof,0)<<endl;
-
- 就是输入到EOF再把数据传入
accumulate
再输出结果。
- 就是输入到EOF再把数据传入
-
- 顺便发一个
istream_iterator
(鸡)和它的孪生兄弟ostream_iterator
(你)的资料包
- 顺便发一个
accumulate
-
accumulate
是一个可以对指定区间内求和的函数。
-
- 格式:
accumulate(起始迭代器,结束迭代器,初始值,自定义操作函数(默认为add))
- 格式:
-
- 例子:
#include<bits/stdc++.h>
using namespace std;
#if 0
自定义操作函数写法:
T 函数名(T a,...){
return a+(...);
}
#endif
int f1(int a,int num){
return a+num*3;
}
struct stu{
int FenShu;
};
int f2(int a,stu b){
return a+b.FenShu;
}
int main(){
vector<int>v{1,2,3,4,5,6,7,8,9,10};
cout<<accumulate(v.begin(),v.end(),0);//初值0+(1+2+3+...+10);
endl(cout);
cout<<accumulate(v.begin(),v.end(),0,f1);//初值0+((1*3)+(2*3)+...+(10*3));
endl(cout);
stu s[]={1,2,3,4,5,6,7,8,9,10};
cout<<accumulate(begin(s),end(s),0,f2);//自己思考
endl(cout);
return 0;
}
-
- 3~7行使用了
#if 0 + #endif
注释法。模糊的说,
- 3~7行使用了
#if 0
#endif
-
- 约等于
/*
*/
-
- 但
#if 0 + #endif
注释法的原理是跳过段,所以它可以保持代码原色。
- 但
#include<bits/stdc++.h>
using namespace std;
int main(){
cout<<"Hello World!"<<endl;
return 0;
}
//多行注释
/*
#include<bits/stdc++.h>
using namespace std;
int main(){
cout<<"Hello World!"<<endl;
return 0;
}
*/
//#if 0 + #endif注释法
#if 0
#include<bits/stdc++.h>
using namespace std;
int main(){
cout<<"Hello World!"<<endl;
return 0;
}
#endif
-
- 25行的
begin()
和end()
可以返回C array
的起始迭代器和结束迭代器。
- 25行的
现在,大家能看懂算法七十三了吗?
The End~
(累死我了~)