加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 如何正确(但有效地)实现像“vector :: insert”这样的东西

发布时间:2020-12-16 04:57:35 所属栏目:百科 来源:网络整理
导读:考虑这个假设的vector实现: templateclass T // ignore the allocatorstruct vector{ typedef T* iterator; typedef const T* const_iterator; templateclass It void insert(iterator where,It begin,It end) { ... } ...} 问题 我们在这里面临一个微妙的
考虑这个假设的vector实现:
template<class T>  // ignore the allocator
struct vector
{
    typedef T* iterator;
    typedef const T* const_iterator;

    template<class It>
    void insert(iterator where,It begin,It end)
    {
        ...
    }

    ...
}

问题

我们在这里面临一个微妙的问题:
开头和结尾有可能引用同一向量中的项目,在此之后.

例如,如果用户说:

vector<int> items;
for (int i = 0; i < 1000; i++)
    items.push_back(i);
items.insert(items.begin(),items.end() - 2,items.end() - 1);

如果它不是指针类型,那我们就没事了.
但是我们不知道,所以我们必须检查[begin,end]是否指向已经在向量内的范围.

但是我们怎么做呢?根据C,如果它们不引用相同的数组,那么指针比较将是未定义的!
所以编译器可能会错误地告诉我们这些项不是别名,实际上它们确实是这样,给了我们不必要的O(n)减速.

潜在的解决方案&警告

一种解决方案是每次复制整个矢量,包括新项目,然后丢弃旧副本.

但是在上面的示例中,这种情况非常缓慢,我们要复制1000个项目只是为了插入1个项目,即使我们显然已经有足够的容量了.

有没有一种通用的方法(正确地)有效地解决这个问题,即在没有任何混叠的情况下没有遭受O(n)减速?

解决方法

你可以使用谓词std :: less etc,它们可以保证给出一个总顺序,即使原始指针比较没有.

从标准[比较] / 8:

For templates greater,less,greater_equal,and less_equal,the specializations for any pointer type yield a total order,even if the built-in operators <,>,<=,>= do not.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读