0

I want to store 256*256 entries in a 2D array. I am doing like this:

struct Data
{
    int Serial_Number;
    int NextIndex;
} ;

struct Data Index[256][256];


Data obj1;
obj1.Serial_Number=1;
obj1.NextIndex=5;

Index[3][240]=obj1;

Now once I have stored all these values then How will I retrieve each value from an array element?

Like I want to retrieve a value stored at Index[3][240].

Secondly, Is this approach faster than unordered_map?

3
  • What is the meaning of the last line of your code Index[3][240]=obj1; ??? I mean are you trying to store a struct obj in int Commented Mar 24, 2014 at 5:43
  • struct Date Index[256][256]? Commented Mar 24, 2014 at 5:45
  • 1
    I made a mistake I have to make an array of Struct Data. Commented Mar 24, 2014 at 5:46

2 Answers 2

1
struct Data
{
    int Serial_Number;
    int NextIndex;
} ;

struct Data Index[256][256]; //should be this

Data obj1;
obj1.Serial_Number=1;
obj1.NextIndex=5;

Index[3][240]=obj1;

retrive the data: struct Data data = Index[3][240];

acceess the struct's data: data.Serial_Number;

Sign up to request clarification or add additional context in comments.

Comments

1

If you want to retrieve each value one by one, just use the index from Index[0][0] to Index [256-1][256-1]. but if you want to access specific element from the array, you need to loop the array to find it.

for(int i = 0; i < 256; ++i)
    for(int j = 0; j < 256; ++j)
        if(Index[i][j] == what you are looking for)
        {
            found!
        }

time complexity of this is O(m*n)(m is the length and n is width of the array) while unordered_map::find() runs in O(1) in the best case, O(n) in worst case (n is the number of elements, this may happen when the hash function is not good leading to too many hash collisions since unordered_map use hash table in its implementation).

2 Comments

Which one should I prefer because I want searching/ retrieving elements to be fast?
even though unordered_map is better than array in the in big O notation aspect, but it's hard to judge which is faster. The elements in array are in contiguous region of memory so that less cache miss occurs if you access the array frequently. you'd better test it on your machine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.