1

firstly I would like to say sorry if this is a repost, onto the question.

Im creating a function which checks certain objects inside a game loop and then returns a boolean value if the check comes back true or false, this is ran a total of 5 times inside my function. I was wondering if it is possible to return an array of all 5 of the boolean values from the function? below is an example of pseudo code which im trying to write:

   Bool funcName(obj obj[])
   {
       for (int i = 0; i < 5; i++)
       {
           boolVal[i]=ChckFunc(obj[i]);  
       }
       return  boolVal[];
   }

Thanks for any help

Elliott
  • 1,347
  • 4
  • 17
  • 23
  • Possible duplicate: [/questions/4264304/howto-return-a-array-in-a-c-method](http://stackoverflow.com/questions/4264304/howto-return-a-array-in-a-c-method) – Theocharis K. Jan 15 '13 at 11:42
  • @Aposperite: I'd say that possible duplicate isn't because it uses dynamically sized arrays where this is more to do with fix sized arrays. – Scott Langham Jan 15 '13 at 11:47

2 Answers2

5

You could return a std::array

std::array<bool, 5> funcName(obj obj[])
{
    std::array<bool, 5> boolArray;
    for (int i = 0; i < 5; i++)
    {
        boolArray[i]=ChckFunc(obj[i]);  
    }
    return  boolArray;
}

or use std::vector if you have a variable number of objects to check

std::vector<bool> funcName(obj obj[], int count)
{
    std::vector<bool> boolArray;
    for (int i = 0; i < count; i++)
    {
        boolArray.push_back(ChckFunc(obj[i]));
    }
    return  boolArray;
}
simonc
  • 41,632
  • 12
  • 85
  • 103
  • Its better to return a pointer instead of a copy. Its a waste of computation time. Refer to my answer for example code. – theV0ID Jan 15 '13 at 11:43
  • You could return a pointer instead but I'd expect that the cost of the heap allocation for the vector would be higher than the cost of the copy construction (plus extra stack use) when we return it by value. If this level of optimisation is important to your program, it'd be worth profiling both versions. – simonc Jan 15 '13 at 11:45
  • 1
    @theVOID: I would have thought the example in this answer would be moved, not copied, and would be about as fast as the pointer version. This would also be safer regarding leaks as there's no requirement on the caller to have to remember to delete the returned data. – Scott Langham Jan 15 '13 at 11:50
0
std::array<bool, 5> funcName( Obj const obj[] )
Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331