从较小类型的指针定义的范围构造向量
Constructing a vector from range defined by pointers of a smaller type
在下面的代码中,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 的文档说:
This constructor has the same effect as vector(static_cast<size_type>(first), static_cast<value_type>(last), a)
if InputIt
is an integral type. (until C++11)
This overload only participates in overload resolution if InputIt
satisfies InputIterator
, to avoid ambiguity with the overload (2). (since C++11)
这个解释没有给我关于我的问题的线索。事实上,这让我更加困惑,因为静态转换的模板参数似乎非常错误......
是的,很安全。所有标准容器都可以从任何迭代器对构造,其中迭代器值类型可以(隐式)转换为容器值类型。这同样适用于 insert
或 assign
.
等函数
您使用的向量构造函数是通过类似于 copy algorithm.
的方式实现的
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++;
需要编译。因此,如果您的类型不同,您可能需要声明一个赋值运算符。
在下面的代码中,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 的文档说:
This constructor has the same effect as
vector(static_cast<size_type>(first), static_cast<value_type>(last), a)
ifInputIt
is an integral type. (until C++11)This overload only participates in overload resolution if
InputIt
satisfiesInputIterator
, to avoid ambiguity with the overload (2). (since C++11)
这个解释没有给我关于我的问题的线索。事实上,这让我更加困惑,因为静态转换的模板参数似乎非常错误......
是的,很安全。所有标准容器都可以从任何迭代器对构造,其中迭代器值类型可以(隐式)转换为容器值类型。这同样适用于 insert
或 assign
.
您使用的向量构造函数是通过类似于 copy algorithm.
的方式实现的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++;
需要编译。因此,如果您的类型不同,您可能需要声明一个赋值运算符。