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";
Oct 18, 2020 Update
Reference:
The follow-up question:
A Summation Function For Various Type Arbitrary Nested Iterable Implementation in C++
The further implementation with c++-concepts:
long double
can be very inefficient on x86 and x86_64, since it will use the 80-bit floating point format, which doesn't fit in SSE registers and thus the compiler then cannot use SSE instructions. Also, what ifT
is astd::complex<float>
? There are many types that you can sum but which don't convert tolong double
. \$\endgroup\$