如何使用STL重构此代码?

时间:2016-04-18 14:01:02

标签: c++ templates stl

这是我的练习代码.. 书籍问题是将此代码重构为模板(使用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);

 .... 
}

5 个答案:

答案 0 :(得分:5)

您可以使用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);

答案 1 :(得分:2)

在此示例中,您可以使用模板SumInt替换SumFloatSum,如下所示:

template <typename T> int Sum(const T* a, int count) {
     T result = 0;
     for (int i = 0; i < count; ++i) {
         result += a[i];
     }
     return result;
}

然后在main()中,您可以致电

int intTotal = Sum(intVals, 3);
float floatTotal = Sum(floatVals, 3);

并且编译器将调用intfloat版本,具体取决于您提供给Sum的参数类型。

答案 2 :(得分:1)

这里我们(sum(...)函数的简单模板):

template <typename T>
T sum(const T* a, size_t count) {
    T result = 0;
    for (size_t i = 0; i < count; ++i) {
        result += a[i];
    }
    return result;
}

int main() {
    const int intVals[] = { 0, 1, 2 };
    const float floatVals[] = { 0.F, 1.F, 2.F };

    const int intTotal = sum(intVals, 3);
    const float floatTotal = sum(floatVals, 3);

    std::cout << "float total: " << intTotal << std::endl;
    std::cout << "int total: " << floatTotal << std::endl;
}

我喜欢std::accumulate,但是:

int main() {
    const auto intVals = { 0, 1, 2 };
    const auto floatVals = { 0.F, 1.F, 2.F };

    const auto intTotal = std::accumulate(intVals.begin(), intVals.end(), 0);
    const auto floatTotal = std::accumulate(floatVals.begin(), floatVals.end(), 0.0F);

    std::cout << "float total: " << intTotal << std::endl;
    std::cout << "int total: " << floatTotal << std::endl;
}

答案 3 :(得分:1)

涉及模板参数和STL(c ++标准库)使用的实现:

#include <iostream>
#include <vector>
#include <cstddef> 

template <typename T>
T Sum(const std::vector<T>& a) {
     T result = 0;
     for (size_t i = 0; i < a.size(); ++i) {
         result += a[i];
     }
     return result;
}


int main() {
    std::vector<int> intVals {0, 1, 2};
    std::vector<float> floatVals {0.F, 1.F, 2.F};

    int intTotal = Sum(intVals);
    float floatTotal = Sum(floatVals);

    std::cout << intTotal << std::endl;
    std::cout << floatTotal << std::endl;
}

请参阅Live Demo

答案 4 :(得分:-1)

您使用此类模板。另请阅读:http://www.cplusplus.com/doc/oldtutorial/templates/

template<typename T>
T doSomething(const T a, int count)
{
  // do your stuff

}

你这样使用它:

int w = 1;
doSomething(w, 1);

在这种情况下,您正在将T替换为int

相关问题