I\'m trying to learn c++ on my own and I\'ve hit a bit of a road block. The problem is I need to take an integer,split it into its digits and get the sum of the digits and
I will put an example up in good faith that you will not reproduce it, if this is a homework assignment, use it as a chance to learn...
// reference: www.cplusplus.com
#include
#include
#include
#include
#include
using namespace std;
// What does this do?
template
struct gen
{
gen(T start) : _num(start) {}
// Do we need these? But why have I commented them out?
//gen(gen const& copy) : _num(copy._num) {}
//gen& operator=(gen const& copy) { _num = copy._num; }
//~gen() {}
// Why do we do this?
T operator()() { T digit = _num % 10; _num /= 10; return digit; }
T _num;
};
// How is this different to the above?
template
bool check_non_zero (T i)
{
return i != 0;
}
// And this? what's going on here with the parameter v?
template
T sum_of_digits(T value, std::vector& v)
{
// Why would we do this?
if (value == 0)
{
v.push_back(0);
return 0;
}
// What is the purpose of this?
v.resize(_size);
// What is this called?
gen gen_v(value);
// generate_n? What is this beast? what does v.begin() return? where did _size come from?
generate_n(v.begin(), _size, gen_v);
// reverse? what does this do?
reverse(v.begin(), v.end());
// erase? find_if? what do they do? what the heck is check_non_zero?
v.erase(v.begin(), find_if(v.begin(), v.end(), check_non_zero));
// what the heck is accumulate?
return accumulate(v.begin(), v.end(), 0);
}
int main()
{
// What does this do?
vector v;
// What is this peculiar syntax? NOTE: 10 here is because the largest possible number of int has 10 digits
int sum = sum_of_digits(123, v);
cout << "digits: ";
// what does copy do? and what the heck is ostream_iterator?
copy(v.begin(), v.end(), ostream_iterator(cout, " "));
cout << endl;
cout << "sum: " << sum << endl;
// other things to consider, what happens if the number is negative?
return 0;
}