【问题标题】:Common print function for all variants of maps C++ STL所有地图变体的通用打印功能 C++ STL
【发布时间】:2020-07-18 14:40:21
【问题描述】:

我正在复习一些关于 C++ STL 的技能,并且我为地图编写了一个基本的插入/删除代码。

下面是代码。 它从用户那里获取一些输入并相应地插入/删除。 非常简单的代码。

但问题是我必须为每个地图变体编写单独的打印函数。
我能做些什么来让它像我们在模板中一样通用吗?

任何帮助将不胜感激。

#include <iostream>
#include <map>
#include <unordered_map>

using namespace std;

void print(const map<int, string>& mp)
{
    cout << "Contents of map: { ";

    for(auto& it: mp)
    {
        cout << it.first << " -> "  << it.second << " ";
    }

    cout << "}" << endl;
}

void print(const multimap<int, string>& mp)
{
    cout << "Contents of multi map: { ";

    for(auto& it: mp)
    {
        cout << it.first << " -> "  << it.second << " ";
    }

    cout << "}" << endl;
}

void print(const unordered_map<int, string>& mp)
{
    cout << "Contents of unordered map: { ";

    for(auto& it: mp)
    {
        cout << it.first << " -> "  << it.second << " ";
    }

    cout << "}" << endl;
}

void print(const unordered_multimap<int, string>& mp)
{
    cout << "Contents of unordered multi map: { ";

    for(auto& it: mp)
    {
        cout << it.first << " -> "  << it.second << " ";
    }

    cout << "}" << endl;
}


int main()
{
    map<int, string> mp1;
    multimap<int, string> mp2;
    unordered_map<int, string> mp3;
    unordered_multimap<int, string> mp4;

    int value = 0;
    string str;

    cout << "Inserting..." << endl;

    while(value >= 0)
    {
        cout << "Enter number: ";
        cin >> value;

        if(value >= 0)
        {
            cout << "Enter string: ";
            cin >> str;

            mp1.insert(pair<int, string>(value, str));
            mp2.insert(pair<int, string>(value, str));
            mp3.insert(pair<int, string>(value, str));
            mp4.insert(pair<int, string>(value, str));
        }
    }

    print(mp1);
    print(mp2);
    print(mp3);
    print(mp4);

    value = 0;

    cout << "Removing..." << endl;

    while(value >= 0)
    {
        cout << "Enter number: ";
        cin >> value;

        if(value >= 0)
        {
            // removing by value
            mp1.erase(value);
            mp2.erase(value);
            mp3.erase(value);
            mp4.erase(value);
        }
    }

    print(mp1);
    print(mp2);
    print(mp3);
    print(mp4);

    return 0;
}

【问题讨论】:

标签: c++ c++11 stl


【解决方案1】:

嗯,是的,确实,模板的用途是什么,对吧?

template<typename T>
void print(const T& mp)
{
    cout << "Contents of map: { ";

    for(auto& it: mp)
    {
        cout << it.first << " -> "  << it.second << " ";
    }

    cout << "}" << endl;
}

只要只有映射或其合理的传真被传递给print()(并且映射中的键和值都具有工作&lt;&lt; 重载),这将起作用。否则,可能需要使用 SFINAE 或 C++20 概念来约束重载决议。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-10
    • 1970-01-01
    相关资源
    最近更新 更多