从较小类型的指针定义的范围构造向量

Constructing a vector from range defined by pointers of a smaller type

本文关键字:范围 向量 定义 指针 小类 类型      更新时间:2023-10-16

在下面的代码中,vector<int>是由int8_t数组构造的。它碰巧有效,但它安全吗?

int8_t *arr;
int arr_size;
... // Filling the array somehow
std::vector<int> v(arr, arr + arr_size); // Is this safe even though we use int8_t* to construct a vector of int?

cppreference.com 的文档说:

如果InputIt是整型类型,则此构造函数与vector(static_cast<size_type>(first), static_cast<value_type>(last), a)具有相同的效果。 (至C++11(

此重载仅在满足InputIterator时才参与重载解析InputIt以避免与重载 (2( 的歧义。 (自C++11起(

这个解释并没有给我关于我的问题的线索。事实上,这让我更加困惑,因为静态强制转换的模板参数似乎非常错误......

是的,这是安全的。 所有标准容器都可以从任何迭代器对构造,其中迭代器值类型可以(隐式(转换为容器值类型。 这同样适用于insertassign等函数。

您正在使用的向量构造函数是使用类似于复制算法实现的。

template<class InputIt, class OutputIt>
OutputIt copy(InputIt first, InputIt last, 
              OutputIt d_first)
{
    while (first != last) {
        *d_first++ = *first++;
     }
    return d_first;
}

如果两种类型大小相同,编译器可以进一步优化并使用memcpy()。但是,这种优化发生在较低的级别,这可能就是让您认为它可能会失败的原因。

需要

做的两件事是输入和输出容器需要匹配的长度(在您的情况下自动完成(和需要编译的*d_first++ = *first++;。因此,如果您的类型不同,则可能需要声明赋值运算符。