The C is the subset of C++ and hence many C programmers that come from embedded background claim they can write proper C++ code. So here is a task (could be a C++ coding homework) that can easily distinguish the C programmers and the modern C++ programmers.
You are given a task to write a function that computes the average for a few numbers. The C way (textbook example) would be:
1 2 3 4 5 | double GetAverage(double *numbers, int length) { double sum = 0.0; for (int i = 0; i < length; ++ i) sum += numbers[i]; return sum / length; } |
double GetAverage(double *numbers, int length) { double sum = 0.0; for (int i = 0; i < length; ++ i) sum += numbers[i]; return sum / length; }
With modern C++ features, you can use std::vector to replace teh error-prone array pointers and use the std::accumulate to apply a reduce-like function to sum up all values.
1 2 3 4 5 6 7 8 | double GetAverage(std::vector<double> numbers) { return (double)std::accumulate(numbers.begin(), numbers.end(), 0, [](const auto &a, const auto &b) { return a + b; } ) / numbers.size(); } |
double GetAverage(std::vector<double> numbers) { return (double)std::accumulate(numbers.begin(), numbers.end(), 0, [](const auto &a, const auto &b) { return a + b; } ) / numbers.size(); }
The above also uses a inline anoymous function delegate that is passed as a parameter. And also the “auto” keyword is modern C++ as well. Also, write some unit tests to test your functions shows your modern development skills:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | #include "stdafx.h" #include "CppUnitTest.h" using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace AverageUtils { TEST_CLASS(AverageTests) { public: TEST_METHOD(Test_AverageWithFourNumbers) { Question1 obj; Assert::AreEqual(2.5, obj.GetAverage({ 1, 2, 3, 4 })); } TEST_METHOD(Test_AverageWithOnlyOneNumber) // test 1 element { Question1 obj; Assert::AreEqual(5.0, obj.GetAverage({ 5 })); } }; } |
#include "stdafx.h" #include "CppUnitTest.h" using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace AverageUtils { TEST_CLASS(AverageTests) { public: TEST_METHOD(Test_AverageWithFourNumbers) { Question1 obj; Assert::AreEqual(2.5, obj.GetAverage({ 1, 2, 3, 4 })); } TEST_METHOD(Test_AverageWithOnlyOneNumber) // test 1 element { Question1 obj; Assert::AreEqual(5.0, obj.GetAverage({ 5 })); } }; }
–EOF (The Ultimate Computing & Technology Blog) —
loading...
Last Post: How to Transform the Values in Excel Files to a Column of Values?
Next Post: How to Design/Implement a Queue using Two Stacks?
Wow, great job! You’ve explained in such a great way about the C++ function to compute the average of numbers. This blog is extremely useful for my kids, I would definitely suggest to my friends, so it can benefit for their kids too.