EXC_BAD_INSTRUCTION在C ++中向量的反向循环

时间:2017-11-03 15:34:50

标签: c++ runtime-error juce

我试图在JUCE中获取ValueTree的路径,用于打开树不同的文件。当试图反向遍历向量(在下面的代码的底部)时,我在完成for循环运行后得到一个错误。错误是" EXC_BAD_INSTRUCTION(代码= EXC_I386_INVOP,子代码= 0x0)"。我假设这是因为一旦for循环完成,它需要从0减去1,这会导致异常。我该怎么做才能避免这个错误,并使用注释掉的代码返回一个字符串?

编辑:path只是一个字符串。此外,使用带符号的值似乎会导致问题,因为我仍然达到-1并导致相同的错误

std::vector<juce::String> propertyPathList;
while (currentTree.isValid())
{
    if (currentTree.isValid() == false)
    {

        break;
    }
    auto currentName = currentTree.getType().toString();
    propertyPathList.push_back (currentName);
    currentTree = currentTree.getParent();
}
String path;
auto listSize = static_cast<unsigned> (propertyPathList.size() - 1);
for (unsigned i = listSize; propertyPathList.size() > i; --i)
{
    DBG (propertyPathList.at (i));
//        path += propertyPathList.at (i);
}

1 个答案:

答案 0 :(得分:0)

这似乎很脆弱:

auto listSize = static_cast<unsigned> (propertyPathList.size() - 1);
for (unsigned i = listSize; propertyPathList.size() > i; --i)
{
    DBG (propertyPathList.at (i));
//        path += propertyPathList.at (i);
}

首先,size()返回一个无符号整数,因此无需强制转换。如果列表为空,则会溢出。

问题是您只想反向浏览此列表,因此编写一个反向循环:

for (auto it = std::rbegin(propertyPathList); it != std::rend(propertyPathList); ++it)
{
    DBG (*it);
//        path += *it;
}