如果将vector <string> path[MAX] 定义在循环体之外,就会报内存错;写进循环体就没事。
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
#define MAX 10
int main() {
string str, cut;
int n;
while (cin >> n && n != 0) {
vector <string> path[MAX];//定义path[第i条路径][第j段]
for (int i = 0; i < n; i++) {
//处理第i条路径
cin >> str;
for (int j = 0; j < str.size(); j++) {
while (str[j] != '\\' && j < str.size()) {
//str最后一个字符可能是反斜杠,也可能是字母
cut += str[j];
j++;
}
path[i].push_back(cut);
cut.clear();
}
}
sort(path, path + n);//对路径排序,按字典序
//第一条路径,直接输出
string space = " ";
for (int j = 0; j < path[0].size(); j++) {
for (int k = j; k > 0; k--) cout << space;//层级与空格数相对应
cout << path[0][j] << endl;
}
//后续路径,与前一条的前缀作对比
for (int i = 1; i < n; i++) {
int same = 0;
while (path[i][same] == path[i - 1][same] && same < path[i - 1].size()) same++;//统计共同前缀的层级数
for (int j = same; j < path[i].size(); j++) {
for (int k = j; k > 0; k--) cout << space;
cout << path[i][j] << endl;
}
}
cout << endl;//最后紧跟一空行
}
return 0;
}