[英]How to add pair vector as a value in std::map?
std::map<Type, vector<std::pair<Value, Integer>>>
I want to create a map like above, so purpose is if i have a lot of dataType and values scrambled, then I want to first check for a dataType and then values of such dataType and then number of time these values occurred. 我想创建一个如上所述的地图,所以目的是如果我有很多dataType和值混乱,那么我想先检查一个dataType,然后检查此类dataType的值,然后检查这些值出现的时间。 For eg:
例如:
DataType: int ,char, string
Values : 23,54,24,78,John, oliver, word ,23
so i want to store something like 所以我想存储像
(int,<(23,2),(54,1),(24,1)>)
similarly for other datatype 对于其他数据类型类似
Using a value which can hold various types 使用可以容纳各种类型的值
For Value
You need a class which allows storing multiple value types. 对于
Value
您需要一个允许存储多种值类型的类。
There is no such class in standard c++ (until c++17, not included). 在标准c ++中没有这样的类(直到c ++ 17,不包括在内)。 You need a library such as boost::variant .
您需要一个库,例如boost :: variant 。 (Boost::variant will become std::variant in c++17)
(Boost :: variant在c ++ 17中将成为std :: variant)
In your case, you can declare the Value type with: 在您的情况下,可以使用以下方法声明值类型:
typedef boost::variant<int, char, std::string> Value;
The map declaration will be: 地图声明将为:
std::unordered_map<Value, int> myMap;
Tested example: 测试示例:
#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 http://melpon.org/wandbox/permlink/B6yttcO9sZJUnKkS
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.