How do I wrap an array?

Can someone please tell me how I would wrap my array. Lets say that it is of size 10. What I want it to do is count the number of letters in the name then mod it into the array (This is working properly). If a name has the same number of letters then it just looks at the next spot. So I need my array to wrap around meaning that if the 10th spot is filled then it would look at the 1st spot in the array. I know that you can do this by using the mod function but am not sure how.Here is my HashTable
1
2
3
4
5
6
7
8
9
10
11
template <class T>
hashTable<T>::hashTable(int Size = 10)
{
	value_arr = new T[Size];
	key_arr = new string[Size];
	status_arr = new int[Size];
	HTableSize = Size;
	// hashIndex + 1 % Size                       //Wrap around
	for (int i = 0; i < Size; i++)
		status_arr[i] = 0;
}


Here is my Hash Function
1
2
3
4
5
6
template <class T>
int hashTable<T>::hashFunction(string key)
{
	return (key.length() - 1) % HTableSize;			
	
}


Here is my add function
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
template <class T>
void hashTable<T>::add(string key, const T &value)
{
	//while (exists() != true)

	//int hashIndex;
	hashIndex = hashFunction(key);					
	
	while (status_arr[hashIndex] == 1)
	{
		hashIndex ++;
	}
	if (status_arr[hashIndex] !=1)
	{
		key_arr[hashIndex] = key;
		value_arr[hashIndex] = value;
		status_arr[hashIndex] = 1;
	}
		
}


Thanks for the help!
If you want to check the next slot:

1
2
3
4
5
// bad:
hashIndex++;

// good:
hashIndex = (hashIndex + 1) % HTableSize;



<side node>

Since mod requires division, which is slow, typically this kind of thing is done with power-of-2 sizes. IE: something like 10 is difficult to work with, but something like 16 works great because you can bitwise-AND with 15 to do the wrapping. Bitwise operations like AND are generally much faster than mod/division

1
2
3
4
5
// this line:
hashIndex = (hashIndex + 1) & 0x0F; // 0x0F = 15 (if you don't know your hex)

// is the same as this line:
hashIndex = (hashIndex + 1) % 0x10; // 0x10 = 16 (if you don't know your hex) 
Topic archived. No new replies allowed.