简体   繁体   中英

easy way to map a range of numbers to a value in cpp

Is there any way to map a range of numbers to a particular number or value in cpp like this:

1-10 : 15

10-20 : 05

the range would be consecutive numbers. the value could be any random number. there is no arithmetic calculation possible on range to derive the value. there is no such relation. I need a hard coded mapping.

Update: I am familiar with maps. consider a map like the one below.

{
    {1,10}
    {2,10}
    {3,10}
    ...
    {10,10}
    {11,20}
    {12,20}
    ...
    {15,20}
    {16,30}
    {17,30}
    {18,30}
}

Instead of doing this for each number, i want to do it for range as value is same for consecutive numbers like below.

{
    {1 to 10  ,10}
    {11 to 15 ,20}
    {16 to 18 ,30}
}

Is there any way to do this.

I know one way to do this which is defining lower bound and upper bound in the array and comparing the input with them.

{
    {1,10,10},
    {11,15,20},
    {15,18,30}
}

It is called Interval Map . There's no built-in data structure for that in C++ but you can make your own or use an existing implementation.

I need a hard coded mapping.

If you can use boost, you can do something like following:

std::unordered_map<std::pair<int, int>, int, boost::hash<std::pair<int, int>>> myMap = {
    { { 1,  10} , 15 },
    { { 10, 20} , 5 },    

};

Otherwise you will have to provide a hash for std::pair :

// A trivial hash function used to hash a pair
struct hash_pair { 
    template <class T1, class T2> 
    size_t operator()(const pair<T1, T2>& p) const
    { 
        auto hash1 = hash<T1>{}(p.first); 
        auto hash2 = hash<T2>{}(p.second); 
        return hash1 ^ hash2; 
    } 
}; 

std::unordered_map<std::pair<int, int>, int, hash_pair> myMap = {
    { { 1,  10} , 15 },
    { { 10, 20} , 5 },    

};

Demo Here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM