DEV Community

dayvonjersen
dayvonjersen

Posted on • Updated on

C++ For Go Programmers: Part 3 - Maps

DISCLAIMER: This series title is inspired by a terrific article on the Go Wiki but, unlike that article, none of the information presented in this series should in any way be taken as sound advice. The author presumes on the part of the reader a competency in both modern C++ and Go which far exceeds the author's own. This is actually a thinly-veiled game devlog

map is easily the worst built-in datatype in Go. I have an outline of the reasons why but we're not about negativity here. Besides, I'm pretty sure someone else has already written that article.

Nope, we're not about that life. We're about exploring wonderful and exciting new possibilities in C++!!! ...by a combination of reinventing the wheel, baby duck syndrome, and eschewing well-defined best practices.

if ok {

In Go, you can access a map value and check if it exists in one step:

m := map[string]int{
    "one": 1,
    "two": 2,
}

one, ok := m["one"]     // 1, true
two, ok := m["two"]     // 2, true
three, ok := m["three"] // 0, false
Enter fullscreen mode Exit fullscreen mode

std::map in C++ does have operator[] but its behavior is different:

Returns a reference to the value that is mapped to a key equivalent to key, performing an insertion if such key does not already exist.

That's not what we want.

std::map::find however, will allow us to determine if a value exists first.

We don't have multiple return values in C++ so we'll have to pass a variable by reference to get the value.

Here goes nothing:

#include <map>

template<typename K, typename V>
bool mapValue(std::map<K,V> m, K key, V& value) {
    auto it = m.find(key);
    if(it != m.end()) {
        value = it->second;
        return true;
    }
    return false;
}
Enter fullscreen mode Exit fullscreen mode

Adapting the Go example above somewhat, use it like this:

std::map<std::string,int> m;
m["one"] = 1;
m["two"] = 2;

int one;
bool success = mapValue(m, std::string("one"), one);
if(success) {
    // ...
}
Enter fullscreen mode Exit fullscreen mode

w00t


This is actually the first time I've made a templated function and it was actually kinda fun even though I know I'm going down the path to ruin here (first you start sprinkling your code with some nice little generics every so often then you start doing metaprogramming next thing you know you're writing compile-time tetris and contributing to Boost)

It should be noted that the implementation here won't work with all types, notably C-style char* strings (hence why I used std::string in the example usage).

And also I probably shouldn't be using std::map at all for storing information for special tiles in my tilemaps but I'm not worried about it it's fine don't worry about it shhhhh

Top comments (0)