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

向量构造函数中的空迭代器范围

  •  5
  • Megamozg  · 技术社区  · 8 年前

    在向量构造函数中传递空迭代器范围有效吗? 也就是说,在下面的代码中它是否是未定义的行为?

    std::set<int> empty_set;
    std::vector<int> target_vector(empty_set.begin(), empty_set.end());
    

    根据 cppreference 说明,此构造函数:

    用范围的内容构造容器[ first , last )

    这是不是意味着 第一 必须是可解引用的?

    2 回复  |  直到 8 年前
        1
  •  8
  •   Toby Speight    8 年前

    构建一个 std::vector 从一个空的范围。如果 first==last ,新向量将没有元素,并且 first 不会被取消引用。

    您所拥有的代码定义良好,并且可以满足您的期望。


    由于指针可以用作迭代器,这甚至意味着此代码定义良好(返回零):

    #include <vector>
    
    int main()
    {
        int const* const p = nullptr;
        std::vector<int> v(p, p);
        return v.size();
    }
    
        2
  •  2
  •   Eduard Rostomyan    8 年前

    不,没有这样的要求。

    它分配了大小为STD::距离(第一,最后)的内存,然后在循环中复制包容。