I am writing a C++ function which takes a positive number and returns an array containing its digits reversed.
#include <cmath>
#include <vector>
std::vector<int> digitize(unsigned long n) {
int x = 1;
for (int i = 1; n >= pow(10,i-1); ++i) { // Supposed to return the correct number of digits
x = i;
}
std::vector<int> result;
for (x; x > 0; --x) { // Takes the number of digits and begin assembling the array in reverse
result[x] = n / pow(10,x-1);
}
return result;
}
During compiling, it returned warnings, and I'm pretty sure the function hasn't even done what I intended it to do yet. One of the warnings had something to do with the for (x; x > 0; --x) loop (some expression is unused). Shouldn't variable x carry over its value from the previous loop?
I tried modifying the second loop to use i instead of x, but as expected, the value and initialization of variable i didn't carry over from the first loop.
I would just rewrite the code to do a simpler approach.
nbeing 0.nand store that value in the vector usingpush_back.nby 10nis 0Example:
Output: