检查元素属于 std::stack

Check that element belongs to std::stack

我在编写代码/函数时遇到问题,该代码/函数将检查提供用户的号码是否属于 std::stack。我尝试过以不同的方式制作它,但我还没有找到任何可行的解决方案。

我试过了:

std::stack<int> myStack;
const bool isInStack = myStack.find(userNumber) != myStack.end(); 

我也试过:

std::stack<int> myStack;
if (myStack.count(userNumber)) {
   // x is in the set, count is 1
} else {
   // count zero, i.e. x not in the set
}

我也尝试编写自己的模板,但我做不到,而且它也没有用。我不知道如何让它工作。

我收到类似 class std::stack<int, std::deque<int, std::allocator<int>>>" has no member "find"

的错误

谁能帮帮我?我真的很生气。

std::stack, but you can use std::deque, which provides the same functionality. Use push_back() for push() and pop_back() for pop(). std::vector中没有find也提供这样的功能

示例代码:

#include <iostream>
#include <deque>
#include <algorithm>
using namespace std;

int main()
{
    deque<int> x;
    for (int i = 1; i <= 5; i++) {x.push_back(i);}

    if (find(x.begin(), x.end(), 5) != x.end()) {cout << "Yes";} else {cout << "No";} 
    cout << "\n";
    if (find(x.begin(), x.end(), 7) != x.end()) {cout << "Yes";} else {cout << "No";}
}

输出:

Yes
No

编辑:std::deque 是一个容器模板,std::stack 建立在它之上(正如@François Andrieux 提到的):

template<
    class T,
    class Container = std::deque<T>
> class stack;
//Defined in header <stack>

文档:

The std::stack class is a container adapter that gives the programmer the functionality of a stack - specifically, a LIFO (last-in, first-out) data structure.

一般来说,它具有基本相同的功能。更多信息 here.

正如其他人所指出的,std::stack 可能不是最好的选择,但假设您没有其他选择,那么您将不得不一个一个地检查堆栈并检查每个元素:

bool found_in_stack(int to_find, std::stack<int> stack) {
    while (!stack.empty()) {
        if (stack.top() == to_find) return true;
        stack.pop();
    }
    return false;
}

请注意,我按值获取堆栈以便制作副本,这样原始堆栈根本不会改变。

如果您不想制作副本,另一种选择是改变原件,这需要临时存储弹出的元素:

bool found_in_stack(int to_find, std::stack<int>& stack) {
    // keep track of elements we've popped here, we'll add them back at the end
    std::stack<int> tmp;

    bool done = false;
    while (!stack.empty()) {
        if (stack.top() == to_find) {
            done = true;
            break;
        }
        
        tmp.push(stack.top());
        stack.pop();
    }

    // add popped elements back
    while (!tmp.empty()) {
        stack.push(tmp.top());
        tmp.pop();
    }
    return done;
}

std::stack 没有 public 接口来检查堆栈中存在的内容而不弹出每个元素并检查它们。

它所拥有的是底层容器的受保护成员变量。

所以如果一定要用std::stack,唯一的办法就是继承它,访问底层容器

template<class T>
class my_stack : private std::stack<T>
{
public:
    using std::stack<T>::stack;
    using std::stack<T>::operator=;

    using std::stack<T>::top;
    using std::stack<T>::empty;
    using std::stack<T>::size;
    using std::stack<T>::push;
    using std::stack<T>::emplace;
    using std::stack<T>::pop;
    using std::stack<T>::swap;
    
    using typename std::stack<T>::const_reference;

    bool contains(const_reference val) const
    {
        return std::find(this->c.begin(), this->c.end(), val) != this->c.end();
    }
};