Search code examples
c++stlgeneric-programming

C++ Generic Programming on Multimap


The multimap is like below:

int main() {
    multimap<int, string> coll;
    coll = { {5, "tagged"} ,
             {2, "a"} ,
             {1, "this"} ,
             {4, "of"} ,
             {6, "strings"} ,
             {1, "is"} ,
             {3, "multimap"} 
          };
}

Now, I'd like to get a function template like below to print all value elements in such containers one by one, including multimap but not limited to this type of map and this particular pair of template parameters.

void PrintAllMaps(multimap<int, string> map) {
    for (auto elem : map) {
        cout << elem.second << ' ';
    }
    cout << endl;
}

Solution

  • including multimap but not limited

    If I understand correctly, you want a template template function:

    template <
        typename T1, 
        typename T2, 
        typename T3, 
        typename T4, 
        template <typename, typename, typename, typename> class M>
    void PrintAllMaps(M<T1, T2, T3, T4>& map) {
        ...
    }
    

    Note that std::multimap and other std::map like containers take actually more than 2 template parameters, the rest of them having default types.

    See the Live Demo