题目是https://www.luogu.com.cn/problem/UVA101
1.如果使用stringstream,则可以正常运行,如下图.
2.如果使用stoi则会抛出异常.如下图
3.完整代码如下
#include<bits/stdc++.h>
using namespace std;
vector<int> block[30];
int n;
void init() {//对木块进行初始化
for (int i = 0; i < n; i++) {
block[i].push_back(i);
}
}
void loc(int num, int& pile, int& height) {//对木块进行定位 以引用的形式返回堆和高度.
for (int i = 0; i < n; i++) {
for (int j = 0; j < block[i].size(); j++) {
if (block[i][j] == num) {
pile = i;
height = j;
return;
}
}
}
}
void goback(int num) {//将num上方的木块进行归位
int pile, height;
pile = 0;
height = 0;
loc(num, pile, height);
for (int i = height + 1; i < block[pile].size(); i++) {
int temp = block[pile][i];
block[temp].push_back(temp);
}
block[pile].resize(height + 1);//重新 指定大小.
}
void move(int num1, int num2) //将num1和其上方的木块放到num2上
{
int pile1, height1, pile2, height2;
pile1 = 0;
height1 = 0;
pile2 = 0;
height2 = 0;
loc(num1, pile1, height1);
loc(num2, pile2, height2);
for (int i = height1; i < block[pile1].size(); i++) {
block[pile2].push_back(block[pile1][i]);
}
block[pile1].resize(height1);
}
void print() {
for (int i = 0; i < n; i++) {
cout << i << ":" << " ";
for (int j = 0; j < block[i].size(); j++) {
cout << block[i][j] << " ";
}
cout << endl;
}
}
void solve() {
string str, str2, str3, str4;
int pile1 = 0, pile2 = 0, height1 = 0, height2 = 0,temp1,temp2;
stringstream sm;
while (cin >> str && str != "quit") {
cin >> str2 >> str3 >> str4;
sm.clear();
sm << str2;
sm >> temp1;
sm.clear();
sm << str4;
sm >> temp2;
loc(temp1, pile1, height1);
loc(temp2, pile2, height2);
/*loc(stoi(str2), pile1, height1); 这种方法不可以为啥呢?
loc(stoi(str4), pile2, height2);*/
if (pile1 == pile2) {
continue;
}
if (str == "move") {
goback(stol(str2));
}
if (str3 == "onto") {
goback(stol(str4));
}
move(stol(str2), stol(str4));
}
}
int main()
{
init();
solve();
print();
return 0;
}