I'm not sure that what you have implemented is a sparse array. I think that the usual way to make a sparse array or matrix is to store the data in an indexed form. The idea is that if you have an array that is 10000 elements in size, but only 100 elements are non-zero, then if you store all the elements specifically you need space for 10000, say, int s. However, if you don't explicitly store the array itself, but pairs of numbers that indicate the index that the number would have in the explicit array, and the value of that element:
class sparse_array
{
public:
/* Public member functions here */
private:
struct sparse_element
{
size_t index;
int value;
};
std::vector< sparse_element > mySparseData;
};
Then, when you want to get a value from the array, you make a get function like this:
int sparse_array::get( size_t i ) const
{
/* handle out-of-range indices here */
/* Get the element from the array */
std::vector< sparse_element >::const_iterator it_find = std::find( mySparseData.begin(), mySparseData.end(), i );
return it_find == mySparseData.end() ? 0 : it_find->second;
}
To make std::find work, you would have to overload operator== for the sparse_element struct to compare with int . Otherwise, you could use a manual for loop.
ravenous
Practically a Master Poster
681 posts since Jul 2005
Reputation Points: 286
Solved Threads: 111
Skill Endorsements: 9