I'm not sure where to declare the sortedInsert function
Function prototypes/declarations are in the header file usually, so other translation units/source file that use the function include the header. The function definition is done in a separate source file. The compiler/linker can then sort out the function exists elsewhere.
do I just add #include<stack> in the header file?
There are three basic ways to do custom includes.
1. Include the standard library headers (and other custom headers) in the header file only, and only the headers the function needs to work. In all source files using the function include the function's header and omit the headers included by the header file.
2. Include the function's header only in source files that use the function, AFTER any standard library headers the function needs to work.
3. Combine 1 & 2. The standard library headers use inclusion guards, custom headers should as well.
Most times I do 3.
C++20 will change when finalized how includes are done with modules.
However the source file doesn't compile. Here is what I am getting:
[Error] variable or field 'sortedInsert' declared void // line 1
[Error] 'stack' was not declared in this scope // line 1
[Note] 'std::stack' // line 1
[Error] expected primary-expression before 'int' // line 1
[Error] expected primary-expression before 'int' // line 1
The errors are based solely around this portion of code from the header file:
void DynIntStack::sortedInsert(stack<int> &stack, int top)
{
if(isEmpty() || top > stack.top()) // base case: stack is empty
{
stack.push(top);
return;
}
// remove the top element
int temp = stack.top();
stack.pop();
sortedInsert(stack, top);
stack.push(temp);
}
void DynIntStack::sortStack()
{
if(!isEmpty())
{
int top = stack.top();
stack.pop();
sortStack(stack);
sortedInsert(stack, top);
}
}
You need to think about:
- what that variable called "stack" is for
- what lifespan you want it to have
- what parts of your code are going to need access to it
Once you've understood those things, it should be easy to figure out what sort of variable it should be.