Moje umiejętności w zakresie STL są słabe. Zastanawiam się, czy jest i tak, aby użyć tej samej funkcji dla kontenera liczb (floats, doubles, ints)? Wydaje się, że powinien istnieć jeden lub dwa liniowy, aby dostosować go do innych typów.
std::accumulate
pozwala zrobić krotnie w stosunku do wszelkich (wejściowego) Zakres iteracyjnej, wykorzystując binarną funkcję, która może przybierać różne typy dla „akumulator” i następnego elementu. W twoim przypadku: funkcja pobierająca std::string
i double
(lub cokolwiek innego), która łączy podany std::string
z wynikiem std::to_string
na drugim parametrze.
template<typename Container>
std::string contents_as_string(Container const & c,
std::string const & separator) {
if (c.size() == 0) return "";
auto fold_operation = [&separator] (std::string const & accum,
auto const & item) {
return accum + separator + std::to_string(item);};
return std::accumulate(std::next(std::begin(c)), std::end(c),
std::to_string(*std::begin(c)), fold_operation);
}
Jak widać, jest to całkowicie niezależne od typu wartości pojemnika. Tak długo, jak możesz przekazać go do std::to_string
jesteś dobry. W rzeczywistości powyższy kod jest niewielką odmianą the example presented for std::accumulate
.
Demo of above function:
int main() {
std::vector<double> v(4);
std::iota(std::begin(v), std::end(v), 0.1);
std::cout << contents_as_string(v, ", ") << std::endl;
std::vector<int> w(5);
std::iota(std::begin(w), std::end(w), 1);
std::cout << contents_as_string(w, " x ") << " = "
<< std::accumulate(std::begin(w), std::end(w), 1, std::multiplies<int>{})
<< std::endl;
}
0,100000, 1,100000, 2,100000, 3,100000
1 x 2 x 3 x 4 x 5 = 120