Beispiellösung
Content |
#ifndef DIM_HPP #define DIM_HPP #include <cstdlib> std::size_t dim(const char* const* argv) { std::size_t count = 0; while (*argv++) ++count; return count; } template<typename T, std::size_t N> constexpr std::size_t dim(const T (&)[N]) { return N; } template<typename T> auto dim(const T& container) -> decltype(container.size()) { return container.size(); } #endif
#ifndef DOTPROD_HPP #define DOTPROD_HPP #include <cassert> #include <iterator> #include "dim.hpp" template<typename A, typename B> auto dotprod(const A& a, const B& b) -> decltype( dim(a), dim(b), std::begin(a) + 3, std::begin(b) + 3, *std::begin(a) + *std::begin(a) * *std::begin(b) ) { using T = decltype(*std::begin(a) * *std::begin(b)); auto len = dim(a); using Index = decltype(len); assert(len = dim(b)); T sum{}; for (Index i = 0; i < len; ++i) { sum += *(std::begin(a) + i) * *(std::begin(b) + i); } return sum; } #endif
#include <iostream> #include <vector> #include "dotprod.hpp" int main() { std::vector<double> a = {2.0, 4.5, 7.0}; int b[] = {4, 5, 6}; std::cout << "a dot b = " << dotprod(a, b) << std::endl; }
theon$ g++ -Wall -o testit testit.cpp theon$ ./testit a dot b = 72.5 theon$
Es geht aber natürlich auch ohne random access und ohne dim:
#ifndef DOTPROD_HPP #define DOTPROD_HPP #include <cassert> #include <iterator> template<typename A, typename B> auto dotprod(const A& a, const B& b) -> decltype( std::end(a), std::end(b), *std::begin(a) + *std::begin(a) * *std::begin(b) ) { using T = decltype(*std::begin(a) * *std::begin(b)); auto it1 = std::begin(a); auto it2 = std::begin(b); T sum{}; for(;;) { bool end1 = it1 == std::end(a); bool end2 = it2 == std::end(b); assert(end1 == end2); if (end1) break; auto val1 = *it1++; auto val2 = *it2++; sum += val1 * val2; } return sum; } #endif
#include <iostream> #include <vector> #include "dotprod2.hpp" int main() { std::vector<double> a = {2.0, 4.5, 7.0}; int b[] = {4, 5, 6}; std::cout << "a dot b = " << dotprod(a, b) << std::endl; }
theon$ g++ -Wall -o testit2 testit2.cpp theon$ ./testit2 a dot b = 72.5 theon$