我想以相反的順序顯示一個句子。例如“我有錢”到“我有錢”。我使用過這樣的堆疊,但我不明白為什么我不能將元素推入我的堆疊(當我最后檢查時,堆疊大小總是 = 0)
#include<bits/stdc .h>
using namespace std;
int main() {
string s;
cin >> s;
string temp;
stack<string> stk;
for (int i = 0; i < s.size(); i ) {
if (s[i] != ' ') {
temp.push_back(s[i]);
cout << temp << endl;
} else {
stk.push(temp);
temp = "";
}
}
for (int i = 0; i < stk.size(); i ) {
cout << stk.top() << endl;
stk.pop();
}
cout << stk.size();
}
uj5u.com熱心網友回復:
這是一個完整的答案。它非常簡短。
#include <stack>
#include <string>
#include <iostream>
int main()
{
std::string temp;
std::stack<std::string> stk;
while (std::cin >> temp)
stk.push(temp);
while (!stk.empty())
{
std::cout << stk.top() << " ";
stk.pop();
}
}
請注意,沒有用于檢查空格的回圈。
其次,while回圈比你的for回圈更直觀,更容易撰寫,這是有缺陷的。在您的for回圈中,您同時有一個縮小的堆疊和一個增加的i索引,這是錯誤的。
在清空堆疊時列印出堆疊條目的正確方法是使用while (not empty)范例,而在回圈內部時,彈出頂部元素。
最后,同樣重要的是,代碼沒有所有的缺陷,例如包含bits標題,以及using namespace std;
現場示例
uj5u.com熱心網友回復:
#include <bits/stdc .h>
using namespace std;
vector <string> splitstringarray;
void splitstring(string s)
{
stringstream ss(s);
string word;
while (ss >> word) {
splitstringarray.push_back(word);
cout << word << endl;
}
}
int main()
{
splitstring("you sample string")
for (int i = splitstringarray.size(); i > 0; i--)
{
cout << splitstringarray[i];
}
return 0;
}
uj5u.com熱心網友回復:
作為變體,您可以考慮此問題的解決方案。
#include <iostream>
#include <vector>
#include <string>
using namespace std;
const int maximumSize=10;
vector<int> visited(maximumSize, 0);
vector<string> sentence={"I", "have", "money"};
vector<string> reverseSentence;
void showContentVector(vector<string> input)
{
for(int i=0; i<input.size(); i)
{
cout<<input[i]<<" ";
}
return;
}
void dfs(int current, int previous)
{
if(visited[current]==1)
{
return;
}
visited[current]=1;
for(int next=(current 1); next<sentence.size(); next)
{
if(next==previous)
{
continue;
}
dfs(next, current);
}
reverseSentence.push_back(sentence[current]);
if(current==0)
{
showContentVector(reverseSentence);
}
return;
}
int main()
{
dfs(0, -1);
return 0;
}
輸入:
I have money
結果如下:
money have I
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/368341.html
