如何防止迭代器超出范围?

时间:2016-11-16 21:10:58

标签: c++ iterator

我正在使用矢量将源行号映射到代码地址。看起来如果address参数高于表中的最高值,则迭代器指向下一个不存在的元素。为了保护错误,我想禁止超出范围的输入参数。有没有比我在下面使用的更优雅的方法?

findLinenoToAddress(unsigned int A)
{
    if (A > AddressToLineMap[AddressToLineMap.size()-1]->Address)
        A = AddressToLineMap[AddressToLineMap.size()-1]->Address;

    std::vector<AddressToLineRecord*>::const_iterator it;
    for(it = AddressToLineMap.begin(); it != AddressToLineMap.end(); it+=1)
    {
        if ((*it)->Address >= A)
            break;
    }
    return (*it)->Lineno;
}

1 个答案:

答案 0 :(得分:1)

事实上,正如AndyG评论的那样,您的代码表明该向量已经过排序。 因此,您应该使用二进制搜索算法: https://en.wikipedia.org/wiki/Binary_search_algorithmWhere can I get a "useful" C++ binary search algorithm?

这就是为什么当前代码很慢并且绝对不应该使用的原因。

但是试图回答确切的问题,对代码的最小更改可能是这样的(注意检查空白和ifs的立即返回):

int findLinenoToAddress(unsigned int A)
{
  if (AddressToLineMap.empty())
      return 0;
  if(A>AddressToLineMap[AddressToLineMap.size()-1]->Address)
      return AddressToLineMap[AddressToLineMap.size()-1]->Lineno;

  std::vector<AddressToLineRecord*>::const_iterator it;
  for(it = AddressToLineMap.begin(); it != AddressToLineMap.end(); it+=1)
    {
      if((*it)->Address >= A) break;
    }
  return (*it)->Lineno;
}

另一种方法是使用“哨兵”: https://en.wikipedia.org/wiki/Sentinel_node

此方法需要您保证您的向量总是在其末尾有UINT_MAX作为地址的附加项目(也意味着它永远不会为空)。 然后代码看起来像这样:

int findLinenoToAddress(unsigned int A)
{
  std::vector<AddressToLineRecord*>::const_iterator it;
  for(it = AddressToLineMap.cbegin(); it != AddressToLineMap.cend(); it++)
    {
      if((*it)->Address >= A)
         return (*it)->Lineno;
    }
  throw "an unreachable code";
}

使用find_if可以大大改善此代码: Using find_if on a vector of object,但它会像其他示例一样慢。 所以再次 - 选择二元搜索。

相关问题