X-Git-Url: https://bilbo.iut-bm.univ-fcomte.fr/and/gitweb/loba.git/blobdiff_plain/6f5ec5fdc42f96a8fe95f4b846b163d4dc92e0c8..a6b73fab30fa59bb7ce701ebec47e52e1d373e26:/cost_func.cpp?ds=sidebyside diff --git a/cost_func.cpp b/cost_func.cpp index c3a463b..4248c56 100644 --- a/cost_func.cpp +++ b/cost_func.cpp @@ -1,57 +1,46 @@ #include -#include -#include +#include #include #include +#include + #include "cost_func.h" cost_func::cost_func(const char* param) { - int len = strlen(param); - char tmpbuf[len + 1]; - char* tmp = tmpbuf; - memcpy(tmp, param, len + 1); - degree = std::count(tmp, tmp + len, ','); - factor = new double[degree + 1]; - for (int i = degree ; i > 0 ; i--) { - char* next = strchr(tmp, ','); - *next++ = '\0'; - std::istringstream(tmp) >> factor[i]; - tmp = next; + std::istringstream paramstream(param); + std::string token; + while (std::getline(paramstream, token, ',')) { + std::istringstream str(token); + double f; + if ((str >> f) && str.eof()) + factors.push_back(f); + else + throw std::invalid_argument("cost_func(): " + "cannot parse \"" + token + "\""); } - std::istringstream(tmp) >> factor[0]; + if (factors.empty()) + throw std::invalid_argument("cost_func(): no factor"); } cost_func::~cost_func() { - delete[] factor; -} - -cost_func& cost_func::operator=(const cost_func& ref) -{ - if (&ref != this) { - degree = ref.degree; - delete[] factor; - factor = new double[degree + 1]; - memcpy(factor, ref.factor, (degree + 1) * sizeof *factor); - } - return *this; } double cost_func::operator()(double amount) const { - double ret = factor[degree]; - for (int i = degree - 1; i >= 0 ; i--) - ret = amount * ret + factor[i]; - return ret; + return std::accumulate(++factors.begin(), factors.end(), factors.front(), + [&amount](double a, double b) { + return amount * a + b; + }); } std::string cost_func::to_string() { std::ostringstream oss; - std::reverse_copy(factor + 1, factor + degree + 1, - std::ostream_iterator(oss, ", ")); - oss << factor[0]; + std::copy(factors.begin(), --factors.end(), + std::ostream_iterator(oss, ", ")); + oss << factors.back(); return oss.str(); }