Search code examples
c++arraysfunction

Is there a way to declare an array = a function that returns an array? (c++)


Let's say I have a function that takes in an integer as an argument and returns an array that has all the digits of the integer separated as a 1D array (pseudocode):

int separatingInt (int num)
{
    int length = amount of digits in num
    int *arr = new int[length]

    for ( int i = length; i > length; i-- )
    {
        arr[i] = num%10
        num = num /10
    }

    return *arr
}

int main()
{
    ifstream file
    file.open("liczby.txt")

    int number
    file >> number

    int* arrayFromNumber = seperatingInt(int num)
}

How do I declare an array from seperatingInt() in main() (referring to the last line in the pseduocode)? Is it better to just separate the digits into an array in seperate?

I was not even sure how to formulate my question properly, so I couldn't find answers myself.

I guess you could do it with a loop in the main() function, but since it's reading numbers from a file, and they all have different amounts of digits, it would look messy. Maybe messy is the way to go, I don't know.


Solution

  • #include <array>
    #include <ranges>
    #include <limits>
    #include <cstdint>
    
    using my_uint = std::uint64_t;
    
    using digit_array =
       std::array<
          std::uint8_t,
          1 + std::numeric_limits<my_uint>::digits10
       >;
    
    digit_array explode_digits(my_uint n){
        digit_array result{};
        for(auto& digit: result | std::views::reverse){
            /*if (n==0) //optimize for speed?
               break;*/
            digit = std::uint8_t(n % 10);
            n /= 10;
        };
        return result;
    };
    
    

    This is what I recommend as beginner stuff, not what academics teach.

    As everyone suggests you can use std::vector, but for a 64 bit number, you only need 20 digits; It's not so much memory that you need to store on heap. If std::uint32_t is used, then the number of digits decreases to just 10, and for std::uint16_t, it'd be just 5.