std::vector::assign/std::vector::operator=(const&) 是否保证在"this"中重用缓冲区?
Does std::vector::assign/std::vector::operator=(const&) guarantee to reuse the buffer in `this`?
如果我将一个向量分配或复制到另一个向量(其容量与前者的大小相同或更大(,我可以假设后者的缓冲区将被重用吗?
下面的示例演示我可以,但是,它是否由标准保证? 在这方面,std::vector::assign
和std::vector::operator=
的行为有什么区别吗?
#include <vector>
#include <iostream>
#include <cassert>
int main()
{
std::vector a {1, 2, 3, 4, 5};
std::vector b {1, 2, 3, 4};
std::vector c {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
std::cout << "1 ==== " << a.capacity() << " " << a.data() << std::endl;
const auto* pa = a.data();
a = b;
assert(pa == a.data());
std::cout << "2 ==== " << a.capacity() << " " << a.data() << std::endl;
a = c;
assert(pa != a.data());
std::cout << "3 ==== " << a.capacity() << " " << a.data() << std::endl;
}
活生生的例子。
更新:这个答案提到
void assign(size_type n, const T& t);
相当于
erase(begin(), end());
insert(begin(), n, t);
标准真的是这样制定的吗,它是否适用于所有std::vector::assign
过载?
简答
不。
不是那么简短的答案
标准不会在vector
上手动定义这些操作。它仅将它们定义为容器的要求。[矢量] 说
向量满足容器和可逆容器(在 [container.requirements] 中的两个表中给出(、序列容器(包括大多数可选序列容器要求 ([sequence.reqmts](、分配器感知容器(表 67(以及连续容器(对于 bool 以外的元素类型(的所有要求。例外情况是未提供的 push_front、pop_front 和emplace_front成员函数。此处仅针对这些表中未描述的向量操作或存在其他语义信息的操作提供说明。
唯一提到这些操作的地方是容器要求和序列容器要求。没有什么支持你的假设。
相关文章:
- 使用std::vector的OpenCL矩阵乘法
- POCO::PostgreSQL:如何将std::vector支持添加到`Binder::bind`
- std::vector的包装器,使数组的结构看起来像结构的数组
- 编译器如何区分std::vector的构造函数
- 使用 pqxx 将 std::vector 存储在 postgresql 中,并从数据库中检索它
- 在std::vector上存储带有模板的类实例
- 在main()之外初始化std::vector会导致性能下降(多线程)
- 为什么std::vector比数组慢
- std::vector::迭代器是否可以合法地作为指针
- 如何将二进制格式的 C++ 对象的 std::vector 保存到磁盘?
- 为什么std::vector和std::valarray初始化构造函数不同
- ";结果类型必须是可从输入范围的值类型""构造的;创建std::vector时
- 在没有未定义行为的情况下实现类似std::vector的容器
- 如何调整 std::vector of Eigen::MatrixXd 的大小
- 使用 std::vector::reverse_iterator 将 int 序列化为字节向量?
- 如何将AERT_Allocate与 std:vector 一起使用
- 推导 std::vector::back() 的返回类型
- 如何将原始字节附加到 std::vector?
- std::vector 没有重载函数的实例与参数列表匹配
- 如果 KEY 是 std::list 或 std::vector 而不是值,那么 std::map 的默认行为是什么?