C++ 推入堆栈的替代方法
我开发了这个程序来添加和检索堆栈中的15$。 我想知道还有没有其他更有效的方法来编写我的代码C++ 推入堆栈的替代方法,c++,stack,push,C++,Stack,Push,我开发了这个程序来添加和检索堆栈中的15$。 我想知道还有没有其他更有效的方法来编写我的代码 #include <iostream> #include <stack> #include <vector> using namespace std; int main() { const int MAX = 100; int count; stack<int, vector<int> > billStack;
#include <iostream>
#include <stack>
#include <vector>
using namespace std;
int main()
{
const int MAX = 100;
int count;
stack<int, vector<int> > billStack;
for (int i=0; i<15; i++) {
billStack.push(i); // add 15 bills onto stack
}
cout << "The stack has " << billStack.size() << " bills.\n";
int cash;
cout << "How many bills to retrieve?\n";
cin >> cash;
for (int i = 0; i< cash; i++) {
billStack.pop();
}
cout << "Cash out :" << cash << ". Remaining: " << billStack.size() << endl;
return 0;
}
#包括
#包括
#包括
使用名称空间std;
int main()
{
常数int MAX=100;
整数计数;
堆垛机;
对于(int i=0;i,考虑到您从未使用堆栈的实际内容,仅使用其大小:
#include <iostream>
using namespace std;
int main()
{
int stackSize = 15;
cout << "The stack has " << stackSize << " bills.\n";
int cash;
cout << "How many bills to retrieve?\n";
cin >> cash;
stackSize -= cash;
cout << "Cash out :" << cash << ". Remaining: " << stackSize << endl;
return 0;
}
#包括
使用名称空间std;
int main()
{
int stackSize=15;
难道我看不到任何明显更有效的方法来写这篇文章,不。这绝对是处理这类事情的最低效代码的最有效版本。(我的意思是,我确实看到了Igor的答案,但我假设你确实出于某种原因想要使用堆栈)我投票将这个问题作为离题题来结束,因为要检查工作代码的问题属于codereview.stackexchange.com。嗯,您可以省去stackSize
变量,也可以省去return 0;
。然后剩下的低效是基于流的I/o,可以用
I/o来代替。我认为这很简单它是……)