How to make function return pointer to vector

Not sure if I'm going about this the right way. I have four vectors (card Hands) of 13 (cards) objects each.

I want this switch statement to be converted into a function to place into a .cpp file. It is currently working fine in main().

lowestCardInPlay.playerWithLowCard is an int from 0-3 which determines if it's players 1-4.

How do i get this function to return a pointer to a vector not an entire vector. unless a vector is a pointer like an array. And how would the pointer look in the function declaration or would it be better to initialize and declare it in the function?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
switch(lowestCardInPlay.playerWithLowCard)
    {
        case 0://If playerOne
            std::cout << "one";
            playerToStart = &playerOne;
            break;
        case 1://If playerTwo
            std::cout << "two";
            playerToStart = &playerTwo;
            break;
        case 2://If playerThree
            playerToStart = &playerThree;
            break;
        case 3://if playerFour
            playerToStart = &playerFour;
            break;
        default:
            std::cout << "There was a glitch in the matrix" << std::endl;
    }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// return pointer to vector
std::vector<int>* foo( std::vector<int>& a,  std::vector<int>& b, int k )
{
    if( k == 0 ) return std::addressof(a) ;
    else if( k == 1 ) return std::addressof(b) ;
    else return nullptr ;
}

// return reference to vector
std::vector<int>& bar( std::vector<int>& a,  std::vector<int>& b, int k )
{
    if( k == 0 ) return a ;
    else if( k == 1 ) return b ;
    else throw std::invalid_argument( "bad k" ) ;
}
So i should pass in the address of all hands and depending on who has the lowest hand that address gets returned? I think i understand that. It also looks like returning reference to vector would work better.

On a side note std::vector in my function declaration is giving my the error:

no type named 'vector' in namespace 'std' did you mean hecto
> It also looks like returning reference to vector would work better.

Yes.

In general:
Use pointers when an object may or may not be present (nullptr if here is no object); use references otherwise.


> no type named 'vector' in namespace 'std'

#include <vector>
I had the #include vector but every time i used vector[i].something to access it i got the error which was only resolved (and this worked) by writing it (*vector)[i].something Something about the vector thinking it was a new container of pointers or something.


Thank you soooo much for your help!
Last edited on
#include vector should be #include <vector> unless it was just a typo in the post
Last edited on
Whoops! was in fact a typo lol. It is #include <vector> . No other vector was having the issue lol.
Topic archived. No new replies allowed.