【问题标题】:Function that mimics remove from standard template library doesn't work correctly模拟从标准模板库中删除的功能无法正常工作
【发布时间】:2014-03-27 01:31:37
【问题描述】:

在大学的 CS 课上,我们被分配了编写几个模仿标准库中的功能模板的函数模板。我已经测试了所有这些,它们都可以工作,除了最后一个“删除”功能。

template <typename T> 
T* remove(T *left, T *right, T &item)
{
  T *element = left; // Need a pointer to the element we are manipulating
  int GoAhead;   // How much in advance is the next element to check
  T *finalElement = right; // The new final pointer of the array.

  while(element < right)
  {
    if(*element == item)
    {
      GoAhead = 0;
      while(element + GoAhead < finalElement)
      {
        T *tempElement = element + GoAhead;
        *tempElement = *(tempElement + 1);
        ++GoAhead;
      }
      --finalElement;
    }
    ++element;
  }
  return finalElement;
}

当数组很小时它工作得很好,但是当数组有很多元素时(在测试中,我们给出了 100000 个元素的数组)由于某种原因它会丢失一些它应该删除的元素。我真的不明白为什么会这样。 有人可以指出我做错了什么吗?

【问题讨论】:

  • 是否应该将while(element &lt; right) 改为while(element &lt; finalElement),以便在删除元素时调整结尾?
  • 我尝试了两种方法,它们给出了相同的结果。而且我认为 while(element
  • 另一个问题是你应该测试新的当前项目是否相等,而不是递增到下一个,以防你有两个或多个匹配的项目一个接一个。
  • 那么,我是否应该在继续之前对其进行测试并再次复制元素?
  • 可能最简单的方法是将element 的增量设置在else 中,这样它仅在*element != item 时才递增,并更改为while(element &lt; finalElement) 以在以下情况下结束循环一切都被提升了。我认为这样做可以。移动太多对我来说似乎仍然效率很低。请参阅下面的答案以获得另一种见解。

标签: c++ arrays templates range


【解决方案1】:

您的函数不适用于 [2, 2, 1, 1, 2, 1, 0, 0, 1, 2],更不用说包含 100000 个元素的数组了。如果您真的模仿标准库中的那些,那么通过将比较等于 val 的元素替换为下一个不等于 val 的元素,并通过返回指向该元素的指针来指示缩短范围的新大小,这会简单得多应该被认为是它的新的过去的元素:

template <typename T> 
T* remove(T *left, T *right, const T &item) // you didn't modify the item, so add a const before it
{
    T* result = left;
    while (left!=right) {
        if (!(*left == item)) {
            *result = *left;
            ++result;
        }
        ++left;
    }
    return result;
}

它返回一个指向该范围新端点的指针。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-03
    • 1970-01-01
    • 1970-01-01
    • 2021-08-02
    • 1970-01-01
    相关资源
    最近更新 更多