使用迭代器的递归调用崩溃

Recursive call with an iterator crashes

本文关键字:调用 崩溃 递归 迭代器      更新时间:2023-10-16

我正在尝试使用迭代器遍历字符串向量,但它需要提前检查一些值。我尝试使用以下代码执行此操作:

typedef std::vector<std::string>::iterator Cursor;
std::string check(Cursor& at) {
    int number;
    std::string ans = *at;
    if (ans.empty()) {
        return "NOT OK";
    } else {
        std::stringstream ss(ans);
        ss >> number >> ans;
        if (ans == "NOT OK") {
            return "NOT OK";
        } else if (ans == "VALUE") {
            int x;
            ss >> x;
            std::string result("OK");
            for (Cursor c = at; x > 0; ++c, --x) {
                result = check(c);
            }
            return result;
        } else {
            return "OK";
        }
    }
}

但是这段代码在进入 for 循环时崩溃了,我不知道为什么。

int x; 
ss >> x; // Here you should check whether x has the expected value.
std::string result("OK");
for (Cursor c = at; x > 0; ++c, --x) { // here you do not check whether c is within boundaries.
  result = check(c);
}
// c should start from at+1, otherwise it may result in infinite recursion.
// Also, termination condition should be added.
for (Cursor c = at+1; x > 0 && c != myVec.end(); ++c, --x) {