Map as a structure in C: use int and struct to determine the value

I used C ++ code and now I'm trying to program in C.

Suppose I defined a structure

struct point{ int x; int y; } 

Is there any data structure A in c that can support the following functions: For two integers, for example i and j , and two points, say p1 and p2 . A[i][j][p1][p2] can uniquely determine a value.

Sounds like a 4 dimensional array. However, indexes are no longer int, but user-defined struct .

Any comments and suggestions are welcome.

+8
c struct indexing map
source share
1 answer

You may have to create your own structure. The C programming language from Kernighan and Ritchie has an example of creating an associated map in c, and what I will discuss below is based on what I remember from this.

Basically, you will need a Map structure containing a struct Key and a struct Value .

 struct Map { struct Key key; struct Value value; }; 

The struct key contains elements that determine the value (in your case, 2 points and 2 intervals)

 struct Key { struct point p1; struct point p2; int i; int j; }; 

struct Value is what you want your key to point to (you didn't say)

You now have a Map structure that links your four inputs to a value, but one map is not that useful. You will need a whole array of them.

 struct Map map[SIZE_OF_MAP]; 

If you donโ€™t want to linearly search for an array for the Map structure you are looking for, you can create a hash function that takes you directly to it. Just define a function that takes the key and uses its value to assign it an index in the array. Use a hash to put the Map in an array and get it from the array. (Note: I'm not sure if this is the correct hashing example, please correct if this is completely wrong)

 int get_hash(Key *key) { int result; /* combine all inputs in some way */ result = key->i * key->i + (key->p1.x * key->p1.x) - (key->p2.x * key->p2.x) /* make sure result isn't out of bounds of the array */ return (result % SIZE_OF_MAP); } 

If you use the hash function, you will need to think about conflicts (what happens when two keys give the same result for get_hash ). When you use your array of maps, you will need some form of collision resolution.

+12
source share

All Articles