简体   繁体   中英

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.).

new is probably not helping anything here. The main purpose of vector is to take care of calling new for you.

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() . 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.

Edit: When making a vector smaller with resize , its memory is usually not freed. 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 .

The best solution is probably to find an existing linear algebra library and use an existing triangular matrix class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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