可以通过以下方式将stack转换为vector:

#include <iostream>
#include <stack>
#include <vector>

using namespace std;

int main() {
    stack<int> s;
    s.push(1);
    s.push(2);
    s.push(3);

    vector<int> v;
    while (!s.empty()) {
        v.push_back(s.top());
        s.pop();
    }

    // 输出vector中的元素
    for (int i : v) {
        cout << i << " ";
    }
    cout << endl;

    return 0;
}

输出结果为:

3 2 1

在上面的代码中,我们首先创建了一个stack 's',并向其中推入了三个整数。然后我们创建了一个空的vector 'v',并在while循环中,每次将stack的顶部元素加入vector中,同时将该元素从stack中弹出。最后,我们遍历vector并输出其中的元素。

C++: 将栈 (Stack) 转换为向量 (Vector)

原文地址: https://www.cveoy.top/t/topic/lARe 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录