1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
|
#include <iostream>
#include <map>
#include <array>
template< std::size_t NDIMENSIONS > using indices = std::array< std::size_t, NDIMENSIONS > ;
template< std::size_t NDIMENSIONS, typename T > using sparse_array = std::map< indices<NDIMENSIONS>, T > ;
template< std::size_t NDIMENSIONS, typename T >
T get( const sparse_array< NDIMENSIONS, T >& arr, const indices<NDIMENSIONS>& pos )
{
const auto iter = arr.find(pos) ;
return iter == arr.end() ? T{} : iter->second ;
}
int main()
{
constexpr std::size_t NDIMS = 4 ;
sparse_array< NDIMS, double > matrix ;
matrix[ { { 35, 123, 7, 196 } } ] = 7.89 ;
matrix[ { { 40, 8, 78, 104 } } ] = 1.2345 ;
matrix[ { { 0, 0, 0, 0 } } ] = -5.682 ;
matrix[ { { 99, 999, 999, 999 } } ] += 3.34 ; // 0.0 + 3.34
std::cout << get( matrix, { { 40, 8, 78, 104 } } ) << '\n' // 1.2345
<< get( matrix, { { 0, 0, 0, 0 } } ) << '\n' // -5.682
<< get( matrix, { { 99, 999, 999, 999 } } ) << '\n' // 3.34
<< get( matrix, { { 15, 100, 62, 4 } } ) << '\n' ; // 0 (not present)
}
|