这是我的练习代码..书籍问题是将此代码重构为模板(使用STL)
我发现了一些书和谷歌,但我没有得到它
你能告诉我一些例子吗?
int SumInt(const int* a, int count) {
int result = 0;
for (int i = 0; i < count; ++i) {
result += a[i];
}
return result;
}
float SumFloat(const float* a, int count) {
float result = 0;
for (int i = 0; i < count; ++i) {
result += a[i];
}
return result;
}
void main() {
int intVals[] = {0, 1, 2};
float floatVals[] = {0.F, 1.F, 2.F};
int intTotal = SumInt(intVals, 3);
float floatTotal = SumFloat(floatVals, 3);
....
}
Run Code Online (Sandbox Code Playgroud)
你可以使用std::accumulate:
int intTotal = std::accumulate(std::begin(intVals), std::end(intVals), 0);
float floatTotal = std::accumulate(std::begin(floatVals), std::end(floatVals), 0.0F);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
95 次 |
| 最近记录: |