c++为下一次迭代保留索引

C++ preserve indexes for next iteration?

本文关键字:一次 迭代 保留 索引 c++      更新时间:2023-10-16

我有一个循环,我想为下一次迭代保留值。我决定使用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);
}

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 '}'
}

Try this

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

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