简体   繁体   English

指向传染媒介的指针向量

[英]Pointer to vector of pointers to vectors

what do I wrong? 我错了什么?

vector<vector<unsigned int> *> *matrix
matrix = new vector<vector<unsigned int> *>(n);
for (vector<vector<unsigned int> *>::size_type i = 0; i < n; i++) {
    matrix->at(i) = new vector<unsigned int>(i + 1);
}

...

The code 编码

vector<int> *myVector2 = new vector<int>(500000000);
for(size_t i = 0; i < myVector->size(); i++) {
    myVector->at(i) = i;
}
delete myVector;

works fine. 工作正常。 I need to work with a very large matrix - so large that it is impossible save the whole matrix and I need to change the memory usage dynamically (sometimes to store only some rows, not all rows are full (I need to see only k first elements of them) etc.). 我需要使用一个非常大的矩阵 - 如此之大以至于无法保存整个矩阵并且我需要动态更改内存使用量(有时只存储一些行,而不是所有行都已满(我需要先看看只有k)他们的元素)等)。

new is probably not helping anything here. new可能在这里没有任何帮助。 The main purpose of vector is to take care of calling new for you. 的主要目的vector是采取调用的护理new给你。

typedef vector<vector<unsigned int> > matrix_t;
matrix_t matrix( n );
std::size_t row_index = 0;
for ( matrix_t::iterator i = matrix.begin(); i != matrix.end(); ++ i ) {
    i.resize( row_index + 1 );
    ++ row_index;
}

When you want to change the number or length of rows, call matrix.resize() or matrix[n].resize() . 如果要更改行的数量或长度,请调用matrix.resize()matrix[n].resize() This minimizes the number of allocations. 这最大限度地减少了分配数量。 But it might be better to map everything to a single, flat vector which is as big as the largest matrix you will need. 但是将所有内容映射到单个平面向量可能会更好,这个向量与您需要的最大矩阵一样大。 Freeing and reallocating things on the fly causes various inefficiencies such as unnecessary cache misses and VM paging. 动态释放和重新分配事物会导致各种低效率,例如不必要的高速缓存未命中和VM分页。

Edit: When making a vector smaller with resize , its memory is usually not freed. 编辑:使用resize使向量更resize ,通常不会释放其内存。 You need to use a trick: 你需要使用一个技巧:

std::vector< unsigned int >( new_row_length ).swap( v );

Note, this only helps when making a vector much smaller; 注意,这只有在使矢量小得多时才有用; when making it larger or the change is small, it's better to stick to resize . 当它变大或变化很小时,最好坚持resize

The best solution is probably to find an existing linear algebra library and use an existing triangular matrix class. 最好的解决方案可能是找到现有的线性代数库并使用现有的三角矩阵类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM