从较小类型的指针定义的范围构造向量
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 的文档说:
如果
InputIt
是整型类型,则此构造函数与vector(static_cast<size_type>(first), static_cast<value_type>(last), a)
具有相同的效果。 (至C++11(此重载仅在满足
InputIterator
时才参与重载解析InputIt
以避免与重载 (2( 的歧义。 (自C++11起(
这个解释并没有给我关于我的问题的线索。事实上,这让我更加困惑,因为静态强制转换的模板参数似乎非常错误......
是的,这是安全的。 所有标准容器都可以从任何迭代器对构造,其中迭代器值类型可以(隐式(转换为容器值类型。 这同样适用于insert
或assign
等函数。
您正在使用的向量构造函数是使用类似于复制算法实现的。
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++;
。因此,如果您的类型不同,则可能需要声明赋值运算符。
相关文章:
- 尝试通过多个向量访问变量时,向量下标超出范围
- 基于范围的 for 循环:迭代使用一个元素扩展的向量
- C++ - 使用基于范围的 for 循环将字符值分配给向量中的字符串不会分配值
- 布尔值向量的基于范围 for 循环
- 如何使用count_if计算向量中的可变数字范围
- 范围 v3 的和向量
- 关于在向量向量上使用基于范围的 for 循环
- 使用基于范围的指针循环和向量时出现C++错误
- 用基于范围的for循环填充指针向量
- 创建结构体向量,表达式:向量下标超出范围
- 代码超出范围.如何动态分配此向量?
- 无法取消引用超出范围的向量迭代器 - 有什么问题?
- 非常量对象的向量似乎在基于范围的 for 循环中被视为常量
- 从给定范围内的向量中查找最大元素
- 向量向量的范围范围
- 将局部变量保存到全局向量中,为什么离开局部范围后可以得到这些局部变量?
- 指针范围问题和返回类中封装的指针向量内的指针引用
- 在 c++ 中检查 if 条件中的向量位置范围
- 向量下标超出向量向量的范围
- C++选项定价函数..单独工作很好,但对于股票价格的范围(向量)来说不行