使用 STL 交换堆栈 C++ 中的第一个和最后一个元素

swapping first and last element in stack c++ using stl

本文关键字:第一个 最后一个 元素 STL 交换 堆栈 C++ 使用      更新时间:2023-10-16

我创建了一个帐户,以便我可以在 STL 中获得有关堆栈的一些帮助,我需要编写一个函数,该函数将堆栈作为参数并将第一个元素与最后一个元素交换,我在网站上搜索了一些帮助,我找到了一个:"https://stackoverflow.com/a/36188943/9990214",我尝试了同样的事情,但我不断收到此错误: 表达式必须具有"int tmp[sz-1];"下带有红线的常量值。 它在到达主节点之前不断给我错误,任何帮助将不胜感激,请记住,我尝试使用 STL 编写函数。 PS :我尝试回复回答问题的人的评论,但它不允许我这样做,因为我需要 50 声誉。

using namespace std;
void rev(stack<int>&x){
int sz=x.size(),mytop,mybottom;
mytop=x.top();
x.pop();
int tmp[sz-1],i=0;
while(!x.empty()){
mybottom=x.top();
tmp[i++]=mybottom;
x.pop();
} 
stack<int> returnIt;
returnIt.push(mybottom);
for(i=0;i<=sz-3;i++){
returnIt.push(tmp[i]);
}
returnIt.push(mytop);
while(!returnIt.empty()){
int tt=returnIt.top();
x.push(tt);
returnIt.pop();
}
}

您收到错误的原因是可变长度数组不是标准C++的一部分。这对您对tmp的定义很重要:

int tmp[sz-1], i=0; //sz is not known at compile-time, therefore, this is invalid code

一些编译器会通过允许 VLA 来允许这样的代码,但不是标准的,你应该使用不同的解决方案。通常,对于这样的任务,std::vector是理想的:

std::vector<int> tmp(sz - 1);
int i = 0;

这应该编译(只要你与其他包含一起#include<vector>(,并且应该具有你期望从代码中得到的行为。

相关文章: