我只是编写一个小程序来将字符串中的字符传输到堆栈并打印出它的最高值.它们只是简单的代码,但有不同的概念,我想问一下哪个代码更有效,为什么?
第一个代码
#include<string>
#include<iostream>
#include<stack>
using namespace std;
int main(){
string str ;
stack<char> s;
cin >> str ;
for(int i=0;i<str.size();i++){
cout << str[i] << "\n";
s.push(str[i]);
cout << "Top of the stack " << s.top() << endl;}
cout << "\n" << endl;
return 0;}
Run Code Online (Sandbox Code Playgroud)
第二个代码使用Iterator
#include<string>
#include<iostream>
#include<stack>
using namespace std;
int main(){
string str ;
stack<char> s;
cin >> str ;
for(string::iterator itr = str.begin();itr!=str.end();itr++){
cout << *itr << "\n";
s.push(*itr);
cout << "Top of the stack " …Run Code Online (Sandbox Code Playgroud)