I need some general advice about how to go about solving this question without over-complicating it any further:
Using an array (and not a linked list), write a member function of the class StackType that updates the stack when a page is referenced. Assuming a stack that can hold 5 values and the next page referenced is 7 then:
the function searches the stack for page 7
if it finds 7, removes it from stack and places it at the top
if is does not find 7 in the list, the last page referenced in the stack is removed and 7 places on top of the stack
Use the following driver function:
void updateRecursive(StackType<Type>& s, Type t);
that calls the recursive function
bool updateRecursiveDo(StackType<Type>& s, Type t);
What I have done so far and I will only include the relevant functions:
I've used the concept of an LRU algorithm to understand what is being asked here.
I understand that the only tools I really have at my disposal is push and pop.
RE: the driver function concept, I always understood this to be my main() program. i.e. the program that calls the function usually done in the case of testing but based on what they've provided me I looked up this detail in a textbook and found that a public driver function would be used to call a private recursive function to keep the no. of parameters in the public function to a minimum.
class StackType {
public:
void updateRecursive(StackType<Type>& s, Type t);
private:
bool updateRecursiveDo(StackType<Type>& s, Type t);
}
template <class Type>
bool StackType<Type>::updateRecursiveDo(StackType<Type>& s, Type t) {
if (isEmptyStack())
return 0;
else if(s.top() == t) {
return 1;
}
else {
s.pop();
updateRecursiveDo(s,t);
}
}
template <class Type>
void StackType<Type>::updateRecursive(StackType<Type>& s, Type t) {
updateRecursiveDo(s,t);
}
So this is great, I call the function in main as follows and I've searched for the 7 and found it:
firstStack.updateRecursive(firstStack, 7);
Now what I'm doing is overthinking how to go about implementing the replacement of the numbers back onto the stack:
Store each item I pop into an array and iterate through each item then push them back onto the stack in each instance
Manually push the items back onto the stack but this wouldn't really work in the event that 7 didn't exist in the list
I am not sure if there is an easier way to deal with a search and replace when a stack is an array?
Several points of order:
I do not see any reason for your updateRecursiveDo() to return anything, be it a bool, or anything else. As I read your question, the purpose of updateRecursiveDo() is really to remove t from your stack, if it exists. Whether it exists, and this function removes it, or not, no longer matters at that point, because the only remaining step to be done would be to push the t value on top of the rebuilt stack.
And that step would occur whether or not t was found in the stack, so returning a bool indicator is irrelevant.
Furthermore, your implementation fails to return a bool value in the third case, so this wouldn't work anyway.
And your version of your updateRecursiveDo() doesn't do this correctly. Let's explain what your function does to your rubber duck:
if the stack is empty, don't do anything.
if the value on the top of the stack is t don't do anything.
otherwise remove the value from the top of the stack, and try again.
To that, your rubber duck would then ask the following logical question: "why are you removing everything on the stack, until you come to the value t, is that what you want to do?"
Of course not, based on the description you gave of your question. My interpretation of the three bullet points in your question is that only the value t should be removed from the stack, and not every value between the value t, and the end of the stack. Which could be the entire stack, if it doesn't contain the value t!
Now, how about you try explaining the following, instead, to your rubber duck:
If the stack is empty, do nothing.
Remove the value from the top of the stack.
If the value is t, do nothing.
Call itself recursively, and when the recursion call returns, push the value back on top of the current stack.
Translated into code, this would be:
template <class Type>
void StackType<Type>::updateRecursiveDo(StackType<Type>& s, Type t)
{
if (isEmptyStack())
return;
auto v=s.top();
if (v == t)
return;
updateRecursiveDo(s, t);
s.push(v);
return;
}
template <class Type>
void StackType<Type>::updateRecursive(StackType<Type>& s, Type t)
{
updateRecursiveDo(s, t);
s.push(t);
}
Think of updateRecursiveDo() as a method to delete an element from a stack. If the element is not found, remove the last one.
And after exit, push t to the top.
You're not replacing t but deleting it, then adding it again.
Use each recursive frame to temporally store the popped value in an internal variable, ie:
Pseudocode:
updateRecursiveDo(stackt stack, page t){
x=stack.pop();
if (x==t) return;
if (stack.empty()) return;
updateRecursiveDo(stack,t);
stack.push(x);
}
Related
I have been struggling with this problem for a few hours now and I've searched for every term that made sense to me. I might even have already read through a relevant answer but didn't recognize it as such because I'm a little confused by pointers.
So, I have a struct that is part of an object which is part of a chain of objects that is "anchored" (if you can call it that) in another object, which is itself part of a chain which is "anchored" in an anchor object initialized in main.
struct values
{
double val, ues;
}
class small
{
public:
values vals;
}
class big
{
public:
small *small_anchor;
}
values &getPointerToStruct(big *con)
{
values *return_vals;
if(con->small_anchor->vals.val==10)
return_vals=con->small_anchor->vals;
return (&return_vals);
}
int main()
{
values *main_values=NULL;//This is supposed to be pointing to the "vals" struct contained inside the "small" object.
big *big_anchor;
big_anchor = new big;
big_anchor->small_anchor = new small;
big_anchor->small_anchor->vals.val=10;
big_anchor->small_anchor->vals.ues=5;
main_values = getPointerToStruct(&big_anchor);//now main_values should be pointing to the "vals" struct
//I want to manipulate the value INSIDE the object itself
main_values.val++;
}
I have tried every combination of &, * and no prefix I could come up with, but nothing would give the result I was hoping for. "Closest" I got was copying "vals" (from inside the object) into "main_values" so that I could manipulate the values there, which isn't of any use to me, as I want to manipulate the SOURCE of the variables.
Also please note that I left out the process of scrolling down the chains to get to the object I was trying to reach and that "return_vals" seems arbitrary, but it happens that there are two possible candidates that could be the struct my program is looking for and the "return_vals" contains the best candidate found so far and is overwritten when a better one is found, or returned when the routine ends.
You wrote
values &getPointerToStruct(big *con)
{
values *return_vals;
if(con->small_anchor->vals.val==10)
return_vals=con->small_anchor->vals;
return (&return_vals);
}
where I think you wanted
values *getPointerToStruct(big *con)
{
values *return_vals = 0;
if(con->small_anchor->vals.val==10)
return_vals=&con->small_anchor->vals;
return (return_vals);
}
But the . in main_values.val++; is wrong anyway. You need to be consistent about whether you wanted to work with a values* or a values&. You could make all this work with a values& if you like, but then main_values should be a values& and not declared until you are ready to initialize it. return_vals would not be practical as a values& because of the stated requirement that the full code gives it a tentative address that is conditionally modified later. But even with return_vals as a values* you could still return a values& if that is what you preferred.
msdn link
text here:
'function call' : recursive call has no side effects, deleting A
function contains a recursive call, but otherwise has no side effects.
A call to this function is being deleted. The correctness of the
program is not affected, but the behavior is. Whereas leaving the call
in could result in a runtime stack overflow exception, deleting the
call removes that possibility.
The code causing this warning is:
template<class Key, class Value>
void Map<Key, Value>::Clear(NodeType* pNode)
{
((Key*) (pNode->m_key))->~Key();
((Value*) (pNode->m_item))->~Value();
NodeType* pL = pNode->GetLeftChild();
NodeType* pR = pNode->GetRightChild();
if (pL != &m_dummy)
{
Clear(pL);
}
if (pR != &m_dummy)
{
Clear(pR);
}
}
and 1 more point: this warning only happens in release build (/Ox)
What is this warning? Thanks!
I'll bet it occurs when ~Key and ~Value are no-ops. The compiler will notice that there is literally nothing else that this function tries to do, so it entirely eliminates this function.
For starters, the warning only happens in a release build because it's the result of an optimization, and the optimizer only runs during release builds.
The optimizer is allowed to restructure or eliminate code, including recursive calls, if it can prove that that will not change the program behavior. There is probably some data-dependent path where one or both calls to Clear() for the left and right nodes would have no effect.
Edit: As #MSalters points out, it is more likely that the destructors for Key and Value are no-ops -- as they would be if Key and Value are both plain-old-data structures or simple types, since the destructors are the only side-effect possible from the function as written.
Edit 2: instead of using placement new, why not use the : initializer?
template struct Map<typename Key, typename Value> {
Key key;
Value value;
Map(Key k, Value v) : key(k), value(v) {}
}
I'd like to know whether there is a way of checking if an element exists or not in the stack.
Assume that the stack interface has push, pop, isEmpty, getTop, member functions.
I know we can do it, if we get the top, compare it with that element and pop it, till it gets empty. But this method would be costy as we'd have to create another stacks to store the pop-ed elements and restore it again.
Here's some pseudo-code for a method that checks for whether or not an element is in the stack:
template<class T>
bool find (stack<T> source, T value)
{
while (!source.isEmpty() && source.top() != value)
source.pop();
if (!source.isEmpty())
return true;
return false;
}
It's critical that the source stack is passed by value, so that it isn't modified. Also, realize that this solution probably isn't as efficient as using a different container than stack and simply calling a method which checks for a value.
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.
I have to return to the previous level of the recursion. is the syntax like below right?
void f()
{
// some code here
//
return;
}
Yes, you can return from a void function.
Interestingly, you can also return void from a void function. For example:
void foo()
{
return void();
}
As expected, this is the same as a plain return;. It may seem esoteric, but the reason is for template consistency:
template<class T>
T default_value()
{
return T();
}
Here, default_value returns a default-constructed object of type T, and because of the ability to return void, it works even when T = void.
Sure. You just shouldn't be returning an actual value.
Yes, you can use that code to return from the function. (I have to be very verbose here to make Stack Overflow not say that my answer is too short)
Yes, that will return from the function to the previous level of recursion. This is going to be very basic explanation, but when you call a function you are creating a new call stack. In a recursive function you are simply adding to that call stack. By returning from a function, whether you return a value or not, you are moving the stack pointer back to the previous function on the stack. It's sort of like a stack of plates. You keep putting plates on it, but than returning moves the top plate.
You could also verify this by using a debugger. Just put a few break points in your code and step through it. You can verify yourself that it works.
The simple answer to this is YES! C++ recognise void method as a function with no return. It basically tells the compiler that whatever happens, once you see the return; break and leave the method....
Yes, sometimes you may wish to return void() instead of just nothing.
Consider a void function that wants to call some pass-through void functions without a bunch of if-else.
return
InputEvent == E_Pressed ? Controller->Grip() :
InputEvent == E_Released ? Controller->Release() :
InputEvent == E_Touched ? Controller->Touch() : void();
You shouldn't have to have the return there, the program will return to the previous function by itself, go into debug mode and step through and you can see it yourself.
On the other hand i don't think having a return there will harm the program at all.
As everyone else said, yes you can. In this example, return is not necessary and questionably serves a purpose. I think what you are referring to is an early return in the middle of a function. You can do that too however it is bad programming practice because it leads to complicated control flow (not single-entry single-exit), along with statements like break. Instead, just skip over the remainder of the function using conditionals like if/else().