I’m trying to implement a stack class from the header file.
I’ve written it using 3 files- stack.h, stack.cpp and main.cpp.
To find an element, I’m using the following code in stack.cpp.
bool stack::find (const string &elem) const
{
vector<string>::const_iterator it = _stack.begin();
return ::find(it,_stack.end(),elem))!=_stack.end();
}
However, find keeps returning false all the time. I’m getting ‘word not found’ each time.
Can you please help me with this?
Here is the pastebin link for the code: PasteBin Link
If you’re doing an iterative lookup, a stack isn’t the data structure you want to use. The point of a stack is that you have to pop off the elements to access them. If you’re going through all of the elements in a search, the only way to preserve the state of the stack is to save all of the elements in a separate container and push them back onto the stack after the search is done. And if you’re doing that, why not just use a random access container like std::vector?
So the answer to your questions is: don’t do that, us a different container.