代码之家  ›  专栏  ›  技术社区  ›  Programmer

序列容器-为什么所有容器都不是所有方法

  •  0
  • Programmer  · 技术社区  · 4 年前

    我通过参考以下信息来学习C++序列容器- https://en.cppreference.com/w/cpp/container [Member function table - functions present in C++03 ,- functions present since C++11, - functions present since C++17, - functions present since C++20] 可在页面末尾找到。

    我无法理解为什么所有序列容器都支持至少是所有基本方法的原因,比如:

    forward_list does not supports size()
    vectors does not support emplace_front()
    arrays does not support capacity()
    deque does not supports reserve()
    list does not supports emplace_hint()
    

    同样,还有其他功能可供选择吗?基本上,是什么特性或功能决定了哪种方法适用于一个容器而不适用于另一个容器?

    0 回复  |  直到 4 年前
        1
  •  4
  •   ypnos    4 年前

    forward_list不支持size()

    std::forward_list旨在实现最大的空间效率,因此大小不会作为额外成员保留(它在std::list中)。要确定大小,必须遍历列表O(N)。

    vectors不支持emplace_front()

    要在前面插入,std::vector首先需要移动现有内容。再次,O(N)。这就是std::dequeue发挥作用的地方。

    数组不支持capacity()

    std::array的大小是固定的,capacity()没有意义,充其量只是size()的复制。

    deque不支持reserve()

    为std::deque保留是没有意义的,因为它不使用连续存储。

    列表不支持emplace_hint()

    std::list上没有emplace_hint()的用例,你可以简单地使用emplace()。