Does the operator [] accepts types other than ints in C++?

Viewed 58

I'm trying to recreate the Dictionary from python into C++, for the sake of learning.

I want to be able to use the subscript operator [] with a keyType (which is the data type of the keys in the dictionary, might be an int, string... etc), I tried this approach (i'm using linked lists):

    // keyFind is the value to be found
    void operator[](keyType keyFind) {
        typeList* trav; // typeList is an alias for: linked_list<keyType, valType>
        for (trav = head; trav != nullptr; trav = trav->next) {
            if (trav->key == keyFind) {
                cout << trav->val << endl;
                break;
            }
        }
    }

The void return type is a place holder for a future return type.

My question is: Should I use this approach or should I simply use a normal function instead, which one is considered Best Practise ?

1 Answers

Does the operator [] accepts types other than ints in C++?

Operator overloads are just functions, and they can accept any parameter types just as other functions can. So, yes.

The C++ standard library already provides std::unordered_map and std::map which are for most purposes analogous to Python dictionaries.

Related