-2

我有一个循环,我想在其中保留下一次迭代的值。我决定使用std::vector它(尽管我不知道这是否是最好的方法)但是当我检查if(bottomMap[i] == true)它时它不会编译。

vector<bool> bottomMap;
for (int i = 0; i < str.size() ; i++){
    if (str[i] != ' ') {
        cout << "XXXX";
    } else {
           if (bottomMap[i] == true)
            cout << "YYYY";
        else
            cout << "X";
        }
    }
    vector <bool> bottomMap(topMap);
}
4

2 回答 2

1

bottomMap 必须在循环开始之前存在

for (int i = 0; i < str.size() ; i++){
    if (str[i] != ' ') {
        cout << "XXXX";
    } else {
           if (bottomMap[i] == true) //< ERROR: bootomMap here is not declred.
            cout << "YYYY";
        else
            cout << "X";
        }
    }
    vector <bool> bottomMap(topMap); //< Declared here, but destroyed to the very next '}'
}

尝试这个

vector <bool> bottomMap(topMap);   //< MOVED HERE
for (int i = 0; i < str.size() ; i++){
    if (str[i] != ' ') {
        cout << "XXXX";
    } else {
           if (bottomMap[i] == true)
            cout << "YYYY";
        else
            cout << "X";
        }
    }
                                  ///< AND NOMORE HERE
}

建议:保持打开和关闭大括号对齐:这将花费更多的行,您将很容易找到事物何时开始和结束它们的存在

这是您的代码,重新对齐:

for (int i = 0; i < str.size() ; i++)
{
    if (str[i] != ' ')  
    {
        cout << "XXXX";
    } 
    else 
    {
        if (bottomMap[i] == true) //< ERROR: bottomMap here is not declared.
            cout << "YYYY";
        else
            cout << "X";
    }
}
vector <bool> bottomMap(topMap); //< Declared here, but too late!
} //< ERROR: TOO CLOSED BRACES
于 2013-04-03T12:34:39.043 回答
0

bottommap因为在你使用它的地方不知道它的定义。你必须在使用它之前定义它。

于 2013-04-03T12:25:23.040 回答