c++arrayscomplex-numbersmultiple-return-values

Return array with const number of members


I wonder how to write function that returns array with constant number of members. Does it make a sense at all? I know I can do something like that:

float* WojtekEQgraph::_Wk_N(float k)
{
    float comp[2];
    comp[0] = cos(-2.0f * double_Pi * (float)k); // Real number
    comp[1] = sin(-2.0f * double_Pi * (float)k); // Imag number

    return comp;
}

And it returns array with two members. But actually "return" commend expect pointer to array and no matter how many members it has. But if in some unpredictable way there will be

float comp[3] or float comp[1] I want return comp; would give me error. How can I do that?

I tried that:

float[2] WojtekEQgraph::_Wk_N(float k)
{
    float comp[2];
    comp[0] = cos(-2.0f * double_Pi * (float)k); // Real number
    comp[1] = sin(-2.0f * double_Pi * (float)k); // Imag number

    return comp;
}

But it doesn't work. For any help thanks in advance.


Solution

  • If you want to return an array object, the C++ standard library spells it as std::array. So applying it to your example:

    std::array<float, 2> WojtekEQgraph::_Wk_N(float k)
    {
        std::array<float, 2> comp;
        comp[0] = cos(-2.0f * double_Pi * (float)k); // Real number
        comp[1] = sin(-2.0f * double_Pi * (float)k); // Imag number
    
        return comp;
    }
    

    Would do it. Other advantages include the lack of dangling references and the need to deal with messy memory allocation. A short and sweet aggregate.

    There's also another answer if you are dealing with complex numbers. Don't re-invent the wheel, and use std::complex instead.