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

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) {

08-26 19:49
查看更多