如何在std :: map中添加对向量作为值


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)>)

类似于其他数据类型

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

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

标准C 中没有此类类(直到C 17,不包括)。您需要一个库,例如boost :: variant。(BOOST ::变体将成为C 17中的STD ::变体)

在您的情况下,您可以用以下方式声明值类型:

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

最新更新