剛學到vector,想說用來解解看堆疊的題目,結果一直遇到這個問題,上網查好像說是跟陣列長度不夠有關,但是vector會有這種問題嗎?又該如何解決呢?
#include <iostream>
#include <vector>
using namespace std;
vector<char> vec;
vector<int>::iterator it;
int main(){
int n;
string a;
cin >> n;
for(int i = 0; i < n; i++){
a = "";
cin >> a;
//如果是空字串
if(a == ""){
cout << "Yes\n";
continue;
}
for(int j = 0; j < a.size(); j++){
if(a[j] == '(' or a[j] == '['){
vec.push_back(a[j]);
}
else{
vec.pop_back();
}
}
vec.empty() == true
? cout << "Yes\n"
: cout << "No\n";
vec.clear();
}
}
我剛改了一次程式碼但仍然會遇到上述的問題,下面是我改的新程式碼
#include <iostream>
#include <vector>
using namespace std;
vector<char> vec;
int main(){
int n;
string a;
cin >> n;
cin.ignore();
for(int i = 0; i < n; i++){
a = "";
getline(cin, a);
if(a == ""){
cout << "Yes\n";
continue;
}
for(int j = 0; j < a.size(); j++){
if(a[j] == '(' or a[j] == '['){
vec.push_back(a[j]);
}
else{
vec.pop_back();
}
}
vec.empty() == true
? cout << "Yes\n"
: cout << "No\n";
vec.clear();
}
}
vec.pop_back();
vec有可能是空的,對空的vector做pop_back會造成undefined behavior
vec.pop_back();
vec有可能是空的,對空的vector做pop_back會造成undefined behavior
好的,謝謝提醒,已解決