How to access array of objects inside member function in C++? - c++

I'm writing an Object Oriented version of FCFS scheduling algorithm, and I've hit a problem. I need to know if there's any way to access an array of objects inside the member function definition, without passing it as a parameter explicitly.
I've tried using "this-pointer", but since the calculation of finish time of current process requires the finish time of the previous, "this" won't work. Or at least I think it won't. I have no idea how to access "previous" object using "this"
void Process :: scheduleProcess(int pid) {
if(pid == 0) finishTime = burstTime;
else finishTime = burstTime +
this->[pid-1].finishTime;
turnAroundTime = finishTime - arrivalTime;
waitingTime = turnAroundTime - burstTime;
}
I can obviously send the array of objects as a parameter and use it directly. I just want to know if there's a better way to do this:
This is the part that's calling the aforementioned function:
for(int clockTime = 0; clockTime <= maxArrivalTime(process);
clockTime++) {
// If clockTime occurs in arrivalTime, return pid of that
process
int pid = arrivalTimeOf(clockTime, process);
if(pid >= 0) {
process[pid].scheduleProcess(pid);
} else continue;
}
Since I'm calling scheduleProcess() using process[pid], which is a vector of objects, I should be able to manipulate the variables pertaining to process[pid] object. How do I access process[pid-1] in the function itself? (Without passing process vector as an argument)

Since scheduleProcess is a member of Process, it only knows what the Process object knows. The previous process is unknown at this level. There are ways that use Undefined Behavior and make more assumptions about your code to get around this, but these should be avoided.
One portable solution to avoid all that is to simply pass in the previous process's finish time as a parameter, since you know this value at the point of the call to scheduleProcess. Where there is not a previous process (the first entry in the array), this finish time would be 0.

Related

Objects vs. Static Variables for retaining function state

I have a function which processes data that comes as a sequence. Because of this, I need to know the value of certain variables from the last function call during the current function call.
My current approach to doing this is to use static variables. My function goes something like this:
bool processData(Object message){
static int lastVar1 = -1;
int curVar1 = message.var1;
if (curVar1 > lastVar1){
// Do something
}
lastVar1 = curVar1;
}
This is just a small sample of the code; in reality I have 10+ static variables tracking different things. My gut tells me using so many static variables probably isn't a good idea, though I have nothing to back that feeling up.
My question: Is there a better way to do this?
An alternative I've been looking into is using an object whose fields are lastVar1, lastVar2, etc. However, I'm not sure if keeping an object in memory would be more efficient than using static variables.
Your question has a taste of being purely about style and opinions, though there are aspects that are not a matter of opinion: multithreading and testing.
Consider this:
bool foo(int x) {
static last_val = -1;
bool result = (x == last_val);
last_val = x;
return result;
}
You can call this function concurrently from multiple threads but it wont do the expected. Moreover you can only test the function by asserting that it does the right thing:
foo(1);
assert( foo(1) ); // silenty assumes that the last call did the right thing
To setup the preconditions for the test (first line) you already have to assume that foo(1) does the right thing, which somehow defeats the purpose of testing that call in the second line.
If the methods need the current object and the previous object, simply pass both:
bool processData(const Object& message,const Object& previous_message){
if (message.var1 > previous_message.var1){
// Do something
return true;
}
return false;
}
Of course this just shifts the issue of keeping track of the previous message to the caller, though thats straight-forward and requires not messing around with statics:
Object message, old_message;
while ( get_more( message )) {
processData(message, old_message);
old_message = message;
}

Accessing an object member var using iterator

I have a vector of (pointers to) objects - people. I have a function that adds income to a person. The problem I'm having is to both find a person and accessing that addInc. I still sometimes get confused with pointers/references and more importantly I'm new to OOP. The relevant function is:
bool Population::Income(const string &id, unsigned int amount) {
Person *Candidate = new Person(id);
//find company using lower_bound
iterPeople = lower_bound(m_People.begin(), m_People.end(), Candidate, cmpId);
if ( iterPeople != m_People.end() && (*iterPeople)->m_id == id ) {
*(iterPeople)->addInc(amount);
//request for member 'addInv' in...maybe you meant to use '->'?
delete Candidate;
return true;
}
delete Candidate;
return false;
The rest of the code is HERE. I have two questions:
How do I solve the addInc issue?
About the lower_bound search - that method should be fine with NewPersonor CancelPerson but Income is gonna get called A LOT. Is that method sufficiently quick? Any way to make it more efficient?
BONUS - with addInc also comes MedianNetworth which returns median of all successfully added Incomes. The efficient way to use this is to create two heaps (min and max). My initial plan was to make_heap in the Population class:
make_heap(m_Audits.begin(), m_Audits.end(), cmpInt);
however I cannot make a heap inside the class because of unexpected '(' token - the very same syntax works in main() or inside any function. What am I doing wrong? Obviously I don't want to create heaps inside functions since I would have to create a new heap whenever I wanted to add an entry.

C++ Unrelated pointer changing after function call

I'm working on using pointers to add objects to a queue and ran into a weird behavioral problem I can't quite figure out.
Each object that gets added to the queue has a 'next' pointer that links them all together and I have a 'start' and 'end' pointer to keep track where each end of the queue is.
The problem I have is that when I pass the end pointer and the object (which is stored in pArray by its processID), it also changes the start pointer -- even though I'm not passing it to the function.
// snippet from my main.cpp
RQCount = 0;
if (RQCount == 0)
{
RQStart = &pArray[processID];
RQStart -> next = &pArray[processID];
endRQ = &pArray[processID];
pArray[processID].setStatus("Ready");
CPUHolder = RQStart;
CPU = RQStart -> CPUBurst;
RQStart ->pStatus = "Executing";
}
else
{
*endRQ = FCFS(endRQ, &pArray[processID]);
pArray[processID].setStatus("Ready")
}
RQCount++;
FCSC Method:
PCB FCFS (PCB *endRQ, PCB *obj)
{
endRQ -> next = obj;
endRQ = obj;
return *endRQ;
};
I've narrowed it down to the function, and what really stumps me is that I move those two lines of code to my main, it runs and behaves just fine. It's when I add the function it doesn't. I think it has to do with how I'm dealing with the pointers and dereferencing, but I could use some help understanding this. Thanks!
EDIT:
To emphasize, I'm not having an issue with variables not changing in the function, as someone marked this a duplicate question for. The issue is after the function is called, it changes RQStart (which is not passed to the function).
If I don't use a function, RQStart stay the same, when I use the function, RQStart changes to a different object.
If you do
RQStart = &pArray[processID];
// ...
endRQ = &pArray[processID];
and then pass endRQ to the function, that will be the same as if you passed RQStart.
So when you change endRQ->next that will also change RQStart->next.
This is one reason for the standard containers to have end() point one past the last element, and not to the last element.

c++ unless wrapper construct for flow control

I have a program part that works similar to the following:
X->updateA();
X->updateB();
X->updateC();
X->updateD();
Each function is supposed to return an integer indicating whether it ran successfully or not, say int ret_val=0 if successful and int ret_val=1 if not.
I am wondering if there exists any wrapper construct that processes each function consecutively as long as ret_val == 0. In my case it shall also call X->updateD(); regardless of the value of ret_val.
Right now I have:
int ret_val = 0;
ret_val = X->updateA();
if (ret_val == 0) ret_val = X->updateB();
if (ret_val == 0) ret_val = X->updateC();
X->updateD();
Which I think is not really readable. What I'd prefer is something similar to the while-loop, although it would have to check for the condition after each function call. Something along the lines of this:
int ret_val = 0;
unless(ret_val != 0)
{
ret_val = X->updateA();
ret_val = X->updateB();
ret_val = X->updateC();
}
X->updateD();
Is there any such construct?
You should use exceptions. Effectively they are an external control flow mechanism which means that you do not have to litter your regular code with error handling and manually propagate every error and check for errors on every call. With exceptions, your original code is perfectly valid as-is and the compiler generates code to check for errors and propagate them to the caller if one occurred.
You should store pointers to the functions you wish to invoke in a container, then iterate over the container. That way you can do whatever you like with the result, and it'll be the same for each function call, without having to repeat that logic n times.

Recursion restarting loop (C++)

I have a question regarding C++. So I have made this program, that computes all possible combinations to solve a problem using recursion(instead of 9 loops). This is a part of the code:
int used[9];
nMin=1000;
void Combinations(int index)
{
if(index>8)
{
return;
}
for(int i=k;i<4;i++)
{
used[index]=i;
if (sum<nMin && Check())//Checks the solution
{
nMin = sum;
used[i]=0;
return;
}
else
{
Combinations(index+1);
}
}
}
The for loop, that should repeat 4 times resets every time recursive call returns. In other words the loop variable is set to 0. Is that just how it works, and do I have to store current loop variable value, or is there another way.
Edit: thank you guys, for detailed information and your answers. The code worked after a few tweaks.
If I am reading this correctly, your question is whether the loop variable i will be protected/preserved by the recursive calls to Combinations.
The answer is yes, the value of the loop counter will be preserved. The reason is scope. Each time the function is called, the stack creates space for a new variable i scoped to the current call. This means all interactions with i during a function call are with the i created for that specific call.
Note: The C/C++ language standards have no explicit notion of a stack. This is actually an implementation detail for the implementation of automatic storage.
int i is a local variable that exists within the context of that for loop for that instance of that function call. When you make a recursive call to the same function, you're pushing a brand new instance of that function call on the stack, which has its own for loop with its own int i variable. They are in no way connected to each other.
If you want all recursive calls to the function to share a counter, you will need to define it as a static variable, and define it outside of the scope of the for loop, like this:
void Combinations(int index)
{
static int persistentCounter;
This will maintain it's value in recursive calls.