c++中括号格式二维数组字符串转vector数组
最近刷力扣碰到官方给的数组都是类似于python那种两层中括号格式,用vs输入要都改成大括号比较费劲,想着将这种格式搞成字符串再转化成二维vector数组,代码是在小浣熊ai写的基础上debug了一下,初学c++比较菜,理解一下。
std::vector<std::vector<int>> convertStringToCppVector(const std::string& str) {
std::vector<std::vector<int>> vectorArray;
std::string temp;
int num = 0;
int bracket_count = 0;
bool neibu = false;
bool fuhao = true;
std::vector<int> currentVector;
for (char ch : str) {
if (ch == '[') {
bracket_count++;
if (bracket_count == 1) neibu=false;
if (bracket_count == 2) neibu=true;
}
else if (ch == ']') {
bracket_count--;
if (bracket_count == 1) {
num = fuhao ? num : -num;
currentVector.push_back(num);
num = 0;
fuhao = true;
neibu = false;
}
if (bracket_count == 0) {
vectorArray.push_back(currentVector);
currentVector.clear();
continue;
}
}
else if (ch == ',' && neibu) {
num = fuhao ? num : -num;
currentVector.push_back(num);
fuhao = true;
num = 0;
}
else if (ch == ',' && not neibu) {
vectorArray.push_back(currentVector);
currentVector.clear();
}
else if (ch == '-') {
fuhao = false;
}
else if (ch == ' ') { continue; }
else {
num = num * 10 + (ch - '0');
}
}
return vectorArray;
}