简体   繁体   中英

std::memcpy and copying data from 2D vector

I have int *a with for 5x4 matrix, where 5 is row and 4 is column.

The memory allocation for a matrix is column are continuous and every row is started after individual column.

I like to copy data from vector< vector <int>> b;

b also have same size and dimension have 5 rows and 4 columns.

How I obtained data for b is

b.resize(5);
for(int i = 0; i < 5; i++){
    b[i].resize(4);
}

I like to copy data from b to a . Is it possible to use std::memcpy(a, &b, sizeof (int)*20) ?

EDIT:

Sorry I like to copy the other way. std::memcpy(&b, a, sizeof (int)*20)

It's not possible to use a single std::memcpy to go from a flattened matrix ( int[] ) to a proper matrix ( std::vector<std::vector<int>> ). For two reasons. First, there is no way to tell std::memcpy the matrix dimensions. Second, the 'rows' in the std::vector matrix are not required to be sequential in memory, but std::memcpy only copies to a single address.

b has aa contiguous buffer in memory, accessible via its data() method. Each element of this buffer is another std::vector , which in turn has its own buffer pointing somewhere else. This means that you can't use a single call to memcpy to copy to all these 2nd level buffers.

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