EXC_BAD_INSTRUCTION对于C++中的向量循环为反向



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

edit: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);
}

这似乎非常脆弱:

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

最新更新