Reputation: 103
I have a list that has stack with int and it is order low to high, by the top of stack. I need to implement the function erase, with a value given in the function. The head of the function would be:
void Delete(list<stack<int> > &L, int element)
In the left it is before call the function, and in the right is how would be the list after to call the function.
Also, the list must be ordered by the top of stack after the execution of the function.
How could I do it in C++?
Thank so much!
Upvotes: 2
Views: 172
Reputation: 5209
There are basically two operations you'd like to implement.
top == element
, erase it.Iterating through the list will look simillar to this
for (auto iter = list.begin(); iter != list.end(); ++iter)
{
// element exists and is equal to required input
// same as !iter->empty()
if (iter->size() && iter->top() == element)
iter->pop();
// deleted last element
// same as iter->empty()
if (!iter->size())
iter = list.erase(iter);
}
And sort is as easy with list::sort
list.sort([](const std::stack<int>& left, const std::stack<int>& right) {
return left.top() < right.top();
});
Edit regarding your question in the comment.
Calling list.sort()
will attempt to sort elements of the list (std::stack<int>
in your code) using operator<
. std::stack
however does not implement such operator for comparisms, thus you have to implement your own function telling the sort method "which elements is smaller than the other" (In your case std::stack<int> left, right
, left
is smaller than right
if left.top() < right.top()
, therefore, comparing first elements of the stack). There are many ways how to provide sort method such function, I used anonymous lambda expression.
Upvotes: 2