Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array with custom indices

Tags:

c++

arrays

So I want to create an array of nine elements, but I want the indices to be specified by me, that is, instead of accesing elements of my array,

std::array<bool,9> myarray

using myarray[0], myarray[1], myarray[2]... I want to access them, for example, as

myarray[21], myarray[34], myarray[100], myarray[9], myarray[56]... 

But still conserving the properties of standard library array and storing only 9 elements.

More specifically, I need an easy access to the elements of a boolean matrix. That is, suppose I have the matrix:

Array<array<bool,100>,100> mymatrix;

And that it is going to be used for checking certain positions (Say position x,y) easily simply using mymatrix[x][y]. I also know that some of the elements are never going to be checked, so they are not really needed. In order to save the most memory possible, the idea is to get rid of those not needed elements, but still conserving the structure to check my elements.

like image 521
D1X Avatar asked Nov 29 '25 01:11

D1X


1 Answers

Such an array is best represented with one of the associative containers provided by the Standard C++ Library - i.e. either a std::map<int,bool> or an std::unordered_map<int,bool>. These containers provide an idiomatic way of doing this in C++.

One added benefit of using an associative container is the ability to iterate the values along with their external "indexes".

If you insist on using an array to store the values, you would have to make your own class that builds a "mapping" between external and internal indexes. This would either take a significant amount of memory for an O(1) access time, use CPU cycles for binary search plus an index-to-index map, use linear search, or hard-code the external indexes.

like image 52
Sergey Kalinichenko Avatar answered Nov 30 '25 14:11

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!