This question is a bit more deceiving than it looks so let me explain.
Suppose I have a class Tournament. One of the member variables is a vector of Player pointers.
class Tournament{
public:
vector <shared_ptr<Player>> playersInTournament;
vector <shared_ptr<Round>> listOfRounds;
//More code.
Suppose I also have a class called Round.
class Round{
public:
vector <shared_ptr<Player>> playersInRound;
Round(playersInTournament);
//More code.
Round has a method called addPlayers(). When I add a player, I want to search the Tournament's playersInTournament vector to see if the player exists.
The problem:
I do not know how to directly refer to playersInTournament because I'm doing it from within the scope of a Round object.
Attempted/Proposed Solutions:
Simply passing playersInTournament into the Round() constructor and creating a copy of it.
I REALLY want to avoid this because it would be a lot of overhead when all I would be using it for is searching. In my head a pointer or a reference to playersInTournament could be more desirable because they'd take less memory once the list becomes big enough.
Creating a reference as class member.
My reasoning for this is Round has a compositional relationship to Tournament. The lifetime of Round will never exceed that of a Tournament object, and also Round does not "own" the vector, it is only meant to be manipulated by Tournament.
The problem I ran into immediately with that is references can't have a lazy initialization. I have nothing to directly reference it to until the round object itself is created, so that doesn't work for me.
And lastly,
Pointer to vector as a class member.
As far as I know, the only way to do this is to use vector.data() which returns pointer to the first element in the array used internally by the vector. This would allow me to iterate through the entire list for validation purposes which is okay, but my intention is to binary search the vector for a matching player and I don't know if I could do that using vector.data().
If there is something I'm missing, or any misconceptions I have please let me know. I could be wrong about using vector.data() but I'm just burnt out for the day and wanted a second opinion because this is a solo project I'm doing for fun.
Thank you for reading!
Best,
Julien Baker Was Right