Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
seeing if stl vector really keeps data contiguous
#include <vector>
#include <iostream>
using namespace std;
typedef float T;
int main()
{
int data_size = 512;
vector<T *> data;
int num_data = 512;
for(int i = 0; i < num_data; i++)
{
T * el = (T *)malloc(sizeof(T) * data_size);
for(int j = 0; j < data_size; j++)
{
el[j] = i*data_size + j;
}
data.push_back(el);
}
bool isItContiguous = true;
T * ptr = data[0];
for(int i = 0; i < num_data; i++)
{
for(int j = 0; j < data_size; j++)
{
if( *(ptr+i*data_size+j) != data[i][j] )
{
cout << i << "," << j << ": " << *(ptr+i*data_size+j) << "," << data[i][j] << " " << endl;
isItContiguous = false;
break;
}
}
if(!isItContiguous)
break;
}
if(isItContiguous)
{
printf("YES, allocated %ld kbytes contiguously.\n", sizeof(T)*data_size*num_data/1024);
}
else
{
printf("NO\n");
}
// free up
for(int i = 0; i < num_data; i++)
{
T * el = data[i];
free(el);
}
vector<vector<T > > ddata;
for(int i = 0; i < num_data; i++)
{
vector<T> el;
el.resize(data_size);
for(int j = 0; j < data_size; j++)
{
el[j] = i*data_size + j;
}
ddata.push_back(el);
}
isItContiguous = true;
ptr = &(ddata[0][0]);
for(int i = 0; i < num_data; i++)
{
for(int j = 0; j < data_size; j++)
{
if( *(ptr+i*data_size+j) != ddata[i][j] )
{
cout << i << "," << j << ": " << *(ptr+i*data_size+j) << "," << ddata[i][j] << " " << endl;
isItContiguous = false;
break;
}
}
if(!isItContiguous)
break;
}
if(isItContiguous)
{
printf("YES, allocated %ld kbytes contiguously.\n", sizeof(T)*data_size*num_data/1024);
}
else
{
printf("NO\n");
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.