028:簡單的foreach
總時間限制: 1000ms 內存限制: 65536kB
描述
編寫MyForeach模板,使程序按要求輸出 不得編寫 MyForeach函數
#include <iostream>
#include <string>
using namespace std;
// 在此處補充你的代碼
void Print(string s)
{cout << s;
}
void Inc(int & n)
{++ n;
}
string array[100];
int a[100];
int main() {int m,n;while(cin >> m >> n) {for(int i = 0;i < m; ++i)cin >> array[i];for(int j = 0; j < n; ++j)cin >> a[j];MyForeach(array,array+m,Print); cout << endl;MyForeach(a,a+n,Inc); for(int i = 0;i < n; ++i)cout << a[i] << ",";cout << endl;}return 0;
}
輸入
多組數據
每組數據第一行是兩個整數 m 和 n ,都不超過 50
第二行是m個不帶空格的字符串
第三行是 n個整數
輸出
對每組數據
第一行輸出所有輸入字符串連在一起的結果
第二行輸出輸入中的每個整數加1的結果
樣例輸入
3 4
Tom Mike Jack
1 2 3 4
1 2
Peking
100 200
樣例輸出
TomMikeJack
2,3,4,5,
Peking
101,201,
來源
Guo Wei
樣例通過代碼:
要點:
- 保證類型一致
- 保證用法與類型一致
template <class T1, class T2>
void MyForeach(T1 start, T1 end, T2 func)
{T1 t;for (t = start; t < end; ++t){func(*t);}
}
template <class T1,class T2>
void MyForeach(T1* startptr,T1* endptr,T2* tempprint)
{T1* temp;for(temp = startptr;temp != endptr;temp++)(*tempprint)(*temp);return;
}