Saurabh Singh
Saurabh Singh

Reputation: 61

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

Upvotes: 1

Views: 376

Answers (1)

galinette
galinette

Reputation: 9292

Using a value which can hold various types

For Value You need a class which allows storing multiple value types.

There is no such class in standard c++ (until c++17, not included). You need a library such as boost::variant. (Boost::variant will become std::variant in c++17)

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

Upvotes: 2

Related Questions