example4_custom_namespace_std_interaction.cpp

 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
26
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>

namespace MyMath {
    template<typename T>
    T sum(const std::vector<T>& numbers) {
        return std::accumulate(numbers.begin(), numbers.end(), T(0));
    }
    
    template<typename T>
    double average(const std::vector<T>& numbers) {
        if (numbers.empty()) return 0.0;
        return static_cast<double>(sum(numbers)) / numbers.size();
    }
}

int main() {
    std::vector<int> data = {1, 2, 3, 4, 5};
    
    std::cout << "Sum: " << MyMath::sum(data) << std::endl;
    std::cout << "Average: " << MyMath::average(data) << std::endl;
    
    return 0;
}
Back to std_namespace