使用 STL 交换堆栈 C++ 中的第一个和最后一个元素
swapping first and last element in stack c++ using stl
我创建了一个帐户,以便我可以在 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>
(,并且应该具有你期望从代码中得到的行为。
相关文章:
- 获取向量C++中第一个值和最后一个值的和
- 查找数组中第一个最小值和最后一个最大值元素之间的算术平均值
- 在类的第一个/最后一个实例存在之前/之后调用一对函数.有没有更好的方法?
- 查询事件日志.如何查询才能单独获取第一个和最后一个事件?
- 我必须更改我的数字最后一个数字和第一个数字,但不要使用仅带有整数或循环的函数.例如从 12345 到 52341
- 如何打印第一个和最后一个元素的和,然后打印第二个和倒数第二个元素的总和,依此类推
- 使用 STL 交换堆栈 C++ 中的第一个和最后一个元素
- 使用数组将最后一个最大值更改为第一个最小值
- "如何使用C++将字符串的第一个和最后一个索引返回到向量中?
- 查找数组的第一个和最后一个索引,其中 from 和 to 元素的顺序总和最大
- 数组:如何在指定索引之前显示数组的第一个和最后一个元素以及数组元素的差异?
- 输入文件中的第一个字符是输出文件中的最后一个字符,反之亦然
- 在向量C++中查找特定的第一个和最后一个索引<float>
- 如何使用第一个、中间和最后一个元素的中位数正确分区?
- 计算第一个和最后一个元素绝对差值较小的子序列 <= K
- COUT:最后一个字符串覆盖第一个字符串
- 获取第 n 项与 std::set 中第一个/最后一个的偏移量
- 如何使用递归返回单链表中的第n个最后一个元素
- 当第一个<=最后一个不满足时,C++标准对算法有什么看法?
- c++函数——哪个日期是第一个/最后一个