I will try to explain my situation a first. I have a class with structure inside of it and an array of this container calss
class A
{
struct B
{
int I;
B *next;
};
B *objOfB; //Array of structures
B *lastB; //Pointer to last objOfB element
public:
//Method for adding values to objOfB
void addB(int i)
{
B *temp = new B;
temp->I = i;
temp->next = NULL;
if(ing == NULL)
{
last = temp;
objOfB = temp;
}
else
{
last->next = temp;
last = temp;
}
}
};
Object's array is used in some functions file
A * objA = A[100];
What I can not figure out is how to hand single value of objOfB. There is a simple example which will go from start to end of objOfB.
for (B *temp = objOfB; temp != NULL; temp = temp->next) {
cout << temp->I << endl;
}
I would like to execute this loop in functions file but I can not think of method which would not return all objOfB (it is used in the first part of the loop B *temp = objOfB;).
Here are the methods I have created to execute this loop:
B listOfBs() { return *objOfB; }
B toNextB() { return *objOfB->next; }
bool noLastB(){ return objOfB->next != NULL; }
And how it works it may be used in the loop:
for (B *temp = listOfBs(); noLastB(); temp = toNextB()) {
cout << temp->I << endl;
}
However I understand that all 3 methods are not suitable for this loop. So I need some method to return value and another one to tell that the next value should be read... Hope not it is clearer what I am trying to achieve.
How to pass container class dynamic arrays of structures value using a method?
From what I understand, you have the class
A(that represents a wrapper of singly-linked list) and this simplestruct Bnested in it :and you want the class
Ato also provide an interface, that would provide the simpler way of iterating through this list.At first, this data member is very confusing:
since you are treating it as a pointer to the first element. Good start would be to rename it to:
B *head;So now each instance ofBcan point to thenextelement and you have the pointer to thehead, last element is the element withnextequal toNULL, you don't needB *lastB;.Then you will realize that methods you tried to provide don't make much sense:
there is no reason why these methods should return by value and since the definition of
struct Bwill have to be visible to the caller anyway. For the sake of KISS principle, just makeheadthe public data member ofAand renameAto more meaningful name, for exampleMyList. Then let the caller do this: