Implementation of fixed size hash map I'm trying to brush up on my algorithms and data structures and wrote a fixed sized hash map assuming both key and value will be only integers. This is a significant simplification of the real case and is supposed to be so. Any comments regarding bugs, best practices, style is gladly appreciated.

#include &lt;vector&gt;
#include &lt;iostream&gt;
#include &lt;exception&gt;
#include &lt;stdexcept&gt;
#include &lt;assert.h&gt;
#define SIZE 10

class HashEntry {
public:
    int _k;
    int _v;
    HashEntry(int k, int v) : _k(k), _v(v) {};
};

class HashMap {
private:
    std::vector&lt;HashEntry&gt; buckets[SIZE];
    int hashFunc(int key);
    std::vector&lt;HashEntry&gt;&amp; getBucket(int key);

public:
    bool keyExists(int k);
    HashEntry get(int k);
    bool put(int k, int v);
    bool remove(int k);
};

int HashMap::hashFunc(int key) {
    return key % SIZE;
}

std::vector&lt;HashEntry&gt;&amp; HashMap::getBucket(int key) {
    if (key &lt; 0) {
        throw std::runtime_error("key should be &gt;= 0");
    }
    return buckets[hashFunc(key)];
}

HashEntry HashMap::get(int k) {
    std::vector&lt;HashEntry&gt;&amp; bucket = getBucket(k);
    for (HashEntry entry : bucket) {
        if (entry._k == k) {
            return entry;
        }
    }
    throw std::runtime_error("Key not found");
}
bool HashMap::keyExists(int k) {
    std::vector&lt;HashEntry&gt;&amp; bucket = getBucket(k);
    for (HashEntry entry : bucket) {
        if (entry._k == k) {

            // key already exists
            return true;
        }
    }
    return false;
}

bool HashMap::put(int k, int v) {
    std::vector&lt;HashEntry&gt;&amp; bucket = getBucket(k);
    if (keyExists(k)) return false;
    bucket.push_back(HashEntry(k, v));
    return true;
}

bool HashMap::remove(int k) {
    std::vector&lt;HashEntry&gt;&amp; bucket = getBucket(k);
    if (!(keyExists(k))) return false;
    for (auto itr = bucket.begin(); itr != bucket.end(); ++itr) {
        HashEntry entry = static_cast&lt;HashEntry&gt;(*itr);
        if (entry._k == k) {
            bucket.erase(itr);
            return true;
            break;
        }
    }
    return false;
}

int main() {
    HashMap map;
    for (int i=0; i &lt; 10; ++i) {
        assert(map.put(i, i*10));
    }
    for (int i=0; i &lt; 10; ++i) {
        assert(map.keyExists(i) == true);
    }
    assert(map.keyExists(0) == true);
    assert(map.get(0)._v == 0);
    assert(map.remove(0) == true);
    assert(map.remove(0) == false);
    assert(map.keyExists(0) == false);

    bool exceptionThrown = false;
    try {
        map.get(0);
    } catch (std::exception &amp;e) {
        exceptionThrown = true;
    };
    assert(exceptionThrown);
    return 1;
}
I would nest HashEntry inside of HashMap as just Entry since it's not very likely to ever stand on its own.



The _ prefix is a bit dangerous as the standard reserves the underscore prefix in a few situations (though not this situation). Still though, it's a bit awkward for it to be there not only in case of bad habits, but also because it serves no purpose. And, map.get(3)._k reads a little oddly.

I would call them key and value. It's just a few more characters to type, and it makes the code read a lot clearer (map.get(3).key).



hashFunc is a bit of an odd name. I would just call it hash instead since it's clearly a function.



std::invalid_argument fits a bit better in getBucket than runtime_error does. The more the type of an exception can tell you, the better (in general -- don't take it to an extreme).



for (HashEntry entry : bucket) {


It probably doesn't matter in practice since HashEntry's are fairly cheap, but this creates a copy of each bucket entry. If HashEntry weren't guaranteed to be such a trivial type, this could be devastating to performance. It should be for (const HashEntry&amp; entry : bucket) {.



Any method that doesn't permute that map should be const (keyExists, get, getBucket). Const correctness is an important part of C++, and it should always be kept in mind when designing/implementing classes.



Why does main return 1? It seems the flow that reaches main is a successful execution, which means that the return value should be 0 (or EXIT_SUCCESS).



You do a lot of the same "loop over and find the correct bucket slot" logic. That should be pulled into a function. That can be done by either making a Bucket type that has the concept searching built in, or, more simply, just write a function that loops over a vector&lt;HashEntry&gt; and returns an iterator to the HashEntry (or end()).



When possible, constants in the form of macros should typically be avoided in favor of const constants. const int SIZE = 10 -- or, since it's being used an array size/index, you might find const std::size_t SIZE = 10; more fitting (I would just stick with an int).

Macros do not have a type, and their names are typically lost as debugging symbols. A const variable has either of those drawbacks, and it also doesn't sacrifice anything.



Since getBucket is a very straightforward constant time operation, it doesn't really matter, but containers activate my super picky mode with regards to performance :).

Try to avoid doing the same work twice. For example, consider your implementation of put. It calls getBucket and it calls keyExists, which behind the scenes calls getBucket. This implies that it might be good to have an additional method behind the scenes and leverage that for checking if keys exists:

bool HashMap::keyExists(const std::vector&lt;HashEntry&gt;&amp; bucket, int k) const {
    for (const HashEntry&amp; entry : bucket) {
        if (entry.key == k) {
            return true;
        }
    }
    return false;
}

bool HashMap::keyExists(int k) const {
    return keyExists(getBucket(k), k);
}

bool HashMap::put(int k, int v) {
    std::vector&lt;HashEntry&gt;&amp; bucket = getBucket(k);
    if (keyExists(bucket, k)) return false;
    bucket.push_back(HashEntry(k, v));
    return true;
}


While I'm being a bit performance paranoid, it would also be better to call getBucket after keyExists in your current implementation. That way, for the case when keys don't exist, you don't bother doing the work of getting the bucket.



HashEntry entry = static_cast&lt;HashEntry&gt;(*itr);


Is this cast necessary? I can't imagine that it is. Also, HashEntry entry = static_cast&lt;HashEntry&gt;(*itr) should be const HashEntry&amp; entry = ... (and really it should be const HashEntry&amp; entry = *itr; or const auto&amp; entry = *itr;).

I also wouldn't bother deferencing the iterator:

if (itr-&gt;key == k) {
    bucket.erase(itr);
    return true;
}




A break; immediately following a return is just noise. Since the function has already been exited, the loop will have been too.



In the spirit of more performance paranoia, it would be nice to allow a single operation for both checking the existence of a key and retrieving the value of it if it does exist. This allows you to avoid the same loop over the bucket twice.

Something like bool find(int key, int&amp; value); or std::pair&lt;bool, int&gt; find(int key) would do the trick (provided it was implemented to take advantage of the ability to do only a single pass).

If you had the concept of an iterator, you could also do this in the form of having a find() that returns an iterator either to the element or to the end(). It's actually a bit icky to do this without iterators since you don't really have anything meaningful to return if you want to avoid a reference parameter. You would have to have either a std::pair&lt;bool, int*&gt; will a null value, or you'd have to have a junk value in the int component of a std::pair&lt;bool, int&gt;. With an int, the junk value approach works pretty well since you can just throw a 0 in it, but if this were to become generic, it becomes more of a concern.



The key in HashEntry should be const since it should never change after construction. Currently this doesn't matter, but if you were ever to return a reference to the HashEntry so that the value could be changed, it would be necessary to maintain the contract of the map. This is why the value_type of std::map&lt;K, V&gt; and std::unordered_map&lt;K, V&gt; is std::pair&lt;const K, V&gt; instead of std::pair&lt;K, V&gt;.



You probably realize this already, but this HashMap is not really a hash map in the strict sense. In particular, it does not honor the expected O(1) lookup and insertion run times. Instead, all of the meaningful operations are all O(n). The unbounded linear scans over the vectors kill it.

There are essentially three main components to a hash table: look up, insertion, and deletion.

The run time of insertion is of course T(lookup) + T(insertion), and with deletion, it's T(lookup) + T(deletion). This means that lookup, insertion, and deletion all have to be constant time operations for insertion and deletion to be constant time.

This means that hashing must be constant time, and it means that whatever is done in the case of a collision must be constant time. In your case, the buckets grow indefinitely, so the lookup across them is linear time. Provided randomly distributed data (which is likely to happen, but bear with me), if you have n keys and S buckets, each bucket will have n/S items in it. A linear scan over that is O(n/S) = O(1) time for constant S.

The easiest solution to this is to make S non-constant. How you do this actually turns out to be relatively important since pathological cases can exploit most approaches. For example, ensuring S &gt;= N/c for some constant c gives you a decent average case, but if keys are not distributed well across buckets, you're essentially back to linear scans.

Another approach might be to decide that whenever a bucket goes over a certain size, double the size of buckets. This would work well at first glance since it would mean resizing and rehashing the map rarely, but once again, pathological cases could purposely target the same bucket so a relatively small amount of keys could cause a hugely sparse map. (Provided the bucket size case was constant, a linear number of keys could cause quadratic growth in the number of buckets).

So, where am I going with this? Go find a well known, well understood, commonly used approach to implementing a hash map, and implement it. I might do linear probing since it's pretty easy to implement and it's relatively drawback free. Other viable approaches can be found on Wikipedia, in a well known implementation (e.g. clang or gcc's unordered_map, or Oracle Java's java.util.HashMap), or in an algorithms text book.