recursion – A Summation Function For Arbitrary Nested Vector Implementation In C++


I am trying to deal with some calculations on nested vector data in C++. The nested vector data may be like std::vector<long double>, std::vector<std::vector<long double>>, or std::vector<std::vector<std::vector<long double>>>. I want to focus on summation here, and the calculation of summation could be done with the Sum function implemented here. Is there any possible improvement of this code?

The function declaration part is as below.

template <class T>
static long double Sum(const std::vector<T> inputArray);
static long double Sum(long double inputNumber);

The function implementation part is as below.

template<class T>
inline long double Sum(const std::vector<T> inputArray)
{
    long double sumResult = 0.0;
    for (auto& element : inputArray)
    {
        sumResult += Sum(element);
    }
    return sumResult;
}

inline long double Sum(long double inputNumber)
{
    return inputNumber;
}

Test for this sum function:

std::vector<long double> testVector1;
testVector1.push_back(1);
testVector1.push_back(1);
testVector1.push_back(1);
std::cout << std::to_string(Sum(testVector1)) + "n";

std::vector<std::vector<long double>> testVector2;
testVector2.push_back(testVector1);
testVector2.push_back(testVector1);
testVector2.push_back(testVector1);
std::cout << std::to_string(Sum(testVector2)) + "n";

std::vector<std::vector<std::vector<long double>>> testVector3;
testVector3.push_back(testVector2);
testVector3.push_back(testVector2);
testVector3.push_back(testVector2);
std::cout << std::to_string(Sum(testVector3)) + "n";
```