C++-STL-矢量-为什么矢量中没有指示relocation_count的工具

C++ - STL - Vector - Why there is no facility to indicate relocation_count in the vector

本文关键字:relocation 指示 count 工具 矢量 为什么 C++-STL-      更新时间:2023-10-16

考虑到预先为向量保留大小有助于提高应用程序和确保在装满时不会发生昂贵的搬迁为什么没有提供重新定位计数的设施在任何给定的时间,这可能非常有助于程序员跟踪最佳在精确容量可能需要根据观测期间的平均值确定确切的数字可能还不清楚。

要计算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(),则计数被忽略(并且可能"忽略"重新分配(。

使用自定义分配器可以解决这个限制。