C ++保留下一次迭代的索引?

时间:2013-04-03 12:22:56

标签: c++

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

2 个答案:

答案 0 :(得分: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
}

Suggetsion:保持开放和关闭大括号:它会花费更多的线条,当事情开始并结束它们的存在时你会很容易找到它

这是你的代码,重新签名:

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

答案 1 :(得分:0)

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