【问题标题】:How to add pair vector as a value in std::map?如何在 std::map 中添加对向量作为值?
【发布时间】:2016-12-05 07:29:42
【问题描述】:
std::map<Type, vector<std::pair<Value, Integer>>>

我想创建一个像上面这样的地图,所以目的是如果我有很多数据类型和值被打乱,那么我想首先检查一个数据类型,然后是这种数据类型的值,然后是这些值发生的次数。 例如:

DataType: int ,char, string 
Values : 23,54,24,78,John, oliver, word ,23

所以我想存储类似的东西

(int,<(23,2),(54,1),(24,1)>)

其他数据类型类似

【问题讨论】:

    标签: c++ dictionary vector


    【解决方案1】:

    使用可以容纳各种类型的值

    对于Value,您需要一个允许存储多种值类型的类。

    标准 c++ 中没有这样的类(直到 c++17,不包括在内)。您需要一个库,例如 boost::variant。 (Boost::variant 在 c++17 中会变成 std​​::variant)

    在您的情况下,您可以声明 Value 类型:

    typedef boost::variant<int, char, std::string> Value;
    

    地图声明将是:

    std::unordered_map<Value, int> myMap;
    

    测试示例:

    #include <iostream>
    #include <boost/functional/hash.hpp>
    #include <boost/variant.hpp>
    #include <string>
    #include <unordered_map>
    #include <typeindex>
    
    //typdedef the variant class as it is quite complicated
    typedef boost::variant<int, char, std::string> Value;
    
    //The map container declaration
    std::map<Value, int> myMap;
    
    int main()
        {
        //insert elements to the map
        myMap[boost::variant<int>(23)]++;
        myMap[boost::variant<int>(23)]++;
        myMap[boost::variant<int>(23)]++;
        myMap[boost::variant<int>(54)]++;
        myMap[boost::variant<int>(24)]++;
    
        myMap[boost::variant<std::string>("John")]++;
        myMap[boost::variant<std::string>("John")]++;
        myMap[boost::variant<char>(60)]++;
    
        //iterate all integers
        std::cout << "Integers:\n";
        for (auto it=myMap.cbegin(); it!=myMap.cend(); ++it)
        {
            if(it->first.type() == typeid(int))
            {
                std::cout << "int=" << boost::get<int>(it->first) << " count=" << it->second << "\n";            
            }
            else if(it->first.type() == typeid(std::string))
            {
                std::cout << "string=\"" << boost::get<std::string>(it->first) << "\" count=" << it->second << "\n";            
            }
            else if(it->first.type() == typeid(char))
            {
                std::cout << "char='" << boost::get<char>(it->first) << "' count=" << it->second << "\n";            
            }
        }
    }
    

    http://melpon.org/wandbox/permlink/B6yttcO9sZJUnKkS

    【讨论】:

    • boost::variant 的文档/示例用法的链接会很好
    • 我认为OP想要使用不同的dataType作为地图的键而不是int,他将有三种dataType:int,char,string。可能更类似于stackoverflow.com/questions/31993839/…
    • 感谢您的评论,答案已重做!
    • 非常感谢您的帮助,但我不想存储类似 myMap[typeid(int)].emplace_back(boost::variant(23),2);我想要的是,当我遇到值 23 时,它应该增加频率,所以如果第一次遇到 23,它应该在下次遇到时存储 (23 ,1),它应该变成 (23,2) 等等。希望这能提供更清晰的画面。
    • 我已经编辑了答案。现在回答你的问题了吗?
    猜你喜欢
    • 2015-07-14
    • 2019-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-04
    相关资源
    最近更新 更多