C++-STL-矢量-为什么矢量中没有指示relocation_count的工具
C++ - STL - Vector - Why there is no facility to indicate relocation_count in the vector
考虑到预先为向量保留大小有助于提高应用程序和确保在装满时不会发生昂贵的搬迁为什么没有提供重新定位计数的设施在任何给定的时间,这可能非常有助于程序员跟踪最佳在精确容量可能需要根据观测期间的平均值确定确切的数字可能还不清楚。
要计算std::vector
的重新分配,std::vector
(或至少它的写访问方法(可能被封装到一个助手类中。
样本代码:
#include <iostream>
#include <vector>
template <typename VALUE>
struct AllocCounter {
std::vector<VALUE> &vec;
unsigned n;
AllocCounter(std::vector<VALUE> &vec): vec(vec), n(0) { }
void push_back(const VALUE &value)
{
size_t old = vec.capacity();
vec.push_back(value);
n += old != vec.capacity();
}
};
int main()
{
std::vector<int> values;
AllocCounter<int> countAllocs(values);
for (int i = 1; i <= 1024; ++i) {
unsigned nOld = countAllocs.n;
countAllocs.push_back(i);
if (countAllocs.n > nOld) std::cout << 'R';
std::cout << '.';
}
std::cout << 'n'
<< "Number of (re-)allocations: " << countAllocs.n << 'n';
// done
return 0;
}
输出:
R.R.R..R....R........R................R................................R................................................................R................................................................................................................................R................................................................................................................................................................................................................................................................R................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................
Number of (re-)allocations: 11
coliru上的实时演示
这个样本是一个概念验证,因为它没有考虑std::vector::emplace()
、std::vector::resize()
等。
Btw。如果直接调用std::vector::push_back()
,则计数被忽略(并且可能"忽略"重新分配(。
使用自定义分配器可以解决这个限制。
相关文章:
- 如何指示结构成员没有锯齿?
- 查找数组中指示性较大但数组中值较小的元素
- " relocation truncated to fit: R_X86_64_PC32 against symbol `__imp_Sleep' "问题
- 如何指示 cmake 的 gcc 版本?
- 如何指示 CMAKE 在 Visual Studio 中使用英特尔 MKL
- 如何设置叮当格式的注释编译指示,以免触及多行doxygen注释?
- C++警告:编译指示在主文件中一次
- C++-STL-矢量-为什么矢量中没有指示relocation_count的工具
- 如何使用 GCC 编译指示启用选项 '-Werror'?
- 为什么 c++ 使用 throw() 关键字来指示函数不会引发任何异常
- scanf() 语句中"%*[^n]"的格式字符串指示什么?分配抑制器 (*) 和否定扫描集 ([^) 如何协同工作?
- wcslen() 在使用编译指示包时返回不正确的结果
- Clang++ 6.0 内存清理器未报告返回值指示条件分支的函数中的未初始化局部变量
- 我怎么知道我最后的指示
- 没有相应 POP 的编译指示包(推送)会导致堆栈粉碎
- 指示 Qi 变换属性失败的适当方法是什么?
- QT "relocation error" / "no version information available"运行时错误
- 如何在 std::bind 中指示给定签名的重载函数?
- 如何指示指针C++所有权
- 是匿名联盟成员平等的指示