Programming and Algorithms (3) Week 7 Quiz (Spring 2018) Part A

Topic URL: http://cxsjsxmooc.openjudge.cn/2018t3springw7/

[1: Simple SumArray]

 

 1  1 #include <iostream>
 2  2 #include <string>
 3  3 using namespace std;
 4  4 template <class T>
 5  5 T SumArray(
 6  6 T* s,T* e){
 7  7  T tmp=*s;
 8  8  for(T* i=s+1;i<e;i++){
 9  9      tmp+=*i;
10 10  }
11 11  return tmp;
12 12 }
13 13 int main() {
14 14     string array[4] = { "Tom","Jack","Mary","John"};
15 15     cout << SumArray(array,array+4) << endl;
16 16     int a[4] = { 1, 2, 3, 4};  //提示:1+2+3+4 = 10
17 17     cout << SumArray(a,a+4) << endl;
18 18     return 0;
19 19 }
View Code

 

[2: Simple foreach]

 1 #include <iostream>
 2 #include <string>
 3 using namespace std;
 4 template<class T1,class T2>
 5 void MyForeach(T1 begin,T1 end,T2 op){
 6     for(T1 i=begin;i<end;i++){
 7         op(*i);
 8     }
 9 }
10 void Print(string s)
11 {
12     cout << s;
13 }
14 void Inc(int & n)
15 {
16     ++ n;
17 }
18 string array[100];
19 int a[100];
20 int main() {
21     int m,n;
22     while(cin >> m >> n) {
23         for(int i = 0;i < m; ++i)
24             cin >> array[i];
25         for(int j = 0; j < n; ++j)
26             cin >> a[j];
27         MyForeach(array,array+m,Print);         
28         cout << endl;
29         MyForeach(a,a+n,Inc);         
30         for(int i = 0;i < n; ++i)
31             cout << a[i] << ",";
32         cout << endl;
33     }
34     return 0;
35 }

[3: Simple Filter]

 1 #include <iostream>
 2 #include <string>
 3 using namespace std;
 4 template<class T1,class T2>
 5 T1 Filter(T1 begin,T1 end ,T1 arr,T2 op){
 6     int index=0;
 7     for(T1 i=begin;i<end;i++){
 8         if(op(*i)){
 9             arr[index++]=*i;
10         }
11     }
12     return (arr+index);
13 }
14 bool LargerThan2(int n)
15 {
16     return n > 2;
17 }
18 bool LongerThan3(string s) 
19 {
20     return s.length() > 3;
21 }
22 
23 string as1[5] = {"Tom","Mike","Jack","Ted","Lucy"};
24 string as2[5];
25 int  a1[5] = { 1,2,3,4,5};
26 int a2[5];
27 int main() {
28     string * p = Filter(as1,as1+5,as2,LongerThan3);
29     for(int i = 0;i < p - as2; ++i)
30         cout << as2[i];
31     cout << endl; 
32     int * p2 = Filter(a1,a1+5,a2,LargerThan2);
33     for(int i = 0;i < p2-a2; ++i)
34         cout << a2[i] << ",";
35     return 0;
36 }

[4: Do you really understand why while(cin >> n) can be established?

 1 #include <iostream>
 2 using namespace std;
 3 class MyCin
 4 {
 5 public:
 6     int flag;
 7     MyCin():flag(0){
 8     }
 9 istream& operator >>(int& x){
10     cin>>x;
11     if(x==-1)
12     exit(0);
13     return cin;
14 }
15 
16 };
17 int main()
18 {
19     MyCin m;
20     int n1,n2;
21     while( m >> n1 >> n2) 
22         cout  << n1 << " " << n2 << endl;
23     return 0;
24 }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325280508&siteId=291194637