Reputation: 263
I am trying to create a multi-dimensional histogram using multi-dimentional vectors and I don't know the dimension size ahead of time. Any ideas on how to do this in c++?
Mustafa
Upvotes: 1
Views: 152
Reputation: 88
vector<vector<int>> mutli_dim_vector_name(num_rows, (vector<int>(num_cols, default_value)));
// You can use this format to further nest to the dimensions you want.
Upvotes: 0
Reputation: 153899
Write your own class. For starters, you'll probably want something along the lines of:
class MultiDimVector
{
std::vector<int> myDims;
std::vector<double> myData;
public:
MultiDimVector( std::vector<int> dims )
: myDims( dims )
, myData( std::accumulate(
dims.begin(), dims.end(), 1.0, std::multiplies<int>() )
{
}
};
For indexing, you'll have to take an std::vector<int>
as the
index, and calculate it yourself. Basically something along the
lines of:
int MultiDimVector::calculateIndex(
std::vector<int> const& indexes ) const
{
int results = 0;
assert( indexes.size() == myDims.size() );
for ( int i = 0; i != indexes.size(); ++ i ) {
assert( indexes[i] < myDims[i] );
results = myDims[i] * results + indexes[i];
}
return results;
}
Upvotes: 3
Reputation: 7034
You can use std::vector, like:
std::vector<std::vector<yourType> >
(or maybe if you use a framework you can search it's documentation for a better integrated array replacement ;) )
Upvotes: 1