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

标签 c++ iterator

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

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

最佳答案

确实,正如 AndyG 评论的那样,您的代码表明 vector 已排序。 正因为如此,你真的应该使用二进制搜索算法: https://en.wikipedia.org/wiki/Binary_search_algorithm , Where 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

此方法需要您保证您的 vector 始终在其末尾具有附加项,并将 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 ,但它会像这里的其他示例一样慢。 所以再次 - 选择二进制搜索。

关于c++ - 如何防止迭代器超出范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40642386/

相关文章:

c++ - 如何在 tchar 中添加格式化字符串(用于多个文件名等)

c++ - 在 C++ 中过度使用 `this`

c++ - 从NULL构造字符串?

Java - 如何在键入时有效地显示单词列表中的单词

java - 迭代器如何绑定(bind)到集合接口(interface)

c++ - 是否有采用投影函数的 min_element 变体?

java - 不使用集合类的二叉搜索树迭代器实现

C++/Windows 多线程同步/数据共享

c++ - 在 C++ 中是否有一种安全的方法将 void* 转换为类指针

java - 使用迭代器的 ArrayList 的不同值的 ArrayList