More generic for_each_tuple Problem In one of previous posts (Readable for_each loop for maps) I have written such code which iterates over range of pairs and “explode” them into the lambda arguments list: C++ template <typename Range, typename Fun> void map_for(const Range& range, Fun f) { for(const auto& e : range) f(e.first, e.second); } 123456 template <typename Range, typename Fun> void map_for(const Range& range, Fun f){ for(const auto& e : range) f(e.first, e.second);} This code is good but it is limited only to containers with pairs (types with defined first and second attributes). What we would like to have… Read More
Generic function which sum up elements from given container Junior task – sum of integers in vector Assume that we have vector of integers ie. C++ auto numbers = std::vector<int>{1,4,7,9,3,4,5}; 1 auto numbers = std::vector<int>{1,4,7,9,3,4,5}; and we want to write function which will sum up all its elements. C++ int sum(const std::vector<int>& numbers) { return std::accumulate(numbers.begin(), numbers.end(), 0); } 1234 int sum(const std::vector<int>& numbers){ return std::accumulate(numbers.begin(), numbers.end(), 0);} In which cases it will work? C++ sum(numbers); // works - result 33 sum(std::vector<int>{1,4,7,9,3,4,5}); // works sum({1,4,7,9,3,4,5}); // works sum(std::vector<double>{1,4,7,9,3,4,5}); // don't work 1234 sum(numbers); // works - result 33sum(std::vector<int>{1,4,7,9,3,4,5}); // workssum({1,4,7,9,3,4,5}); // workssum(std::vector<double>{1,4,7,9,3,4,5}); // don't work Middle task – sum of elements in vector no matter what type Let’s make it more generic… Read More