矢量载体,备用 [英] Vector of vectors, reserve
问题描述
假设我想将 int
的二维矩阵表示为向量的向量:
Suppose I want to represent a two-dimensional matrix of int
as a vector of vectors:
std::vector<std::vector<int> > myVec;
内部尺寸为常数,例如5,外部尺寸小于或等于 N
。为了最大限度地减少重新分配,我想保留空间:
The inner dimension is constant, say 5, and the outer dimension is less than or equal to N
. To minimize reallocations I would like to reserve space:
myVec.reserve(N);
内部向量的大小是多少?这纯粹取决于实现吗?这如何影响数据的空间局部性?由于内部尺寸是一个常量,有没有办法告诉编译器使用这个常量大小?如果内部向量的大小发生变化,这些答案将如何改变?
What size is assumed for the inner vector? Is this purely implementation dependent? How does this effect the spatial locality of the data? Since the inner dimension is a constant is there a way to tell the compiler to use this constant size? How do these answers change if the inner vector's size changes?
推荐答案
由于内部维度是恒定的,我想您想要
Since your inner dimension is constant, I think you want
std::vector< std::array<int, 5> > vecs;
vecs.reserve(N);
这将为您提供预分配的连续存储,这对于性能而言是最佳的。
This will give you preallocated contiguous storage, which is optimal for performance.
这篇关于矢量载体,备用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!