Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to achieve the following? C++ "advanced" map/list/array?

I am trying to create some sort of list, map or what ever may be suggested that does the following

something [] = { 
        mainvalue1 = 2001 { 
            value2 = 1905
            value3 = 2000
            result = 500

            value2 = 1910
            value3 = 2030
            result = 700
        } 
        mainvalue2 = 2005 { 
            value2 = 1635
            value3 = 2070
            result = 300

            value2 = 2310
            value3 = 5930
            result = 599
        } 
}

cout << "result: " << something[2001][1905][2000] << endl;

result: 500

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

cout << "result: " something[2001][1910][2030] << endl;

result: 700

cout << "result: " something[2005][2310][5930] << endl;

result: 599

Is this possible? I would appreciate if someone could guide me how to start my thought process or give me an example how this can be achievable in C++

>Solution :

I find your structure utterly confusing, but it’s possible to make the lookup nearly like you want it:

#include <iostream>
#include <map>
#include <vector>

int main() {
    std::map<int, std::map<std::vector<int>, int>> something{
        {2001, {
            {{1905, 2000}, 500},
            {{1910, 2030}, 700}
        }},
        {2005, {
            {{1635, 2070}, 300},
            {{2310, 5930}, 599}
        }}
    };

    std::cout << "result: " << something[2001][{1905,2000}] << '\n';
    //>> result: 500

    std::cout << "result: " << something[2001][{1910,2030}] << '\n';
    //>> result: 700

    std::cout << "result: " << something[2005][{2310,5930}] << '\n';
    //>> result: 599
}

If there are always two values (value2 and value3) in the above std::vector<int>, you can replace it with a std::pair<int, int> instead:

std::map<int, std::map<std::pair<int, int>, int>> something[...};

Note: A std::map is ordered (with respect to the keys in the map). If you don’t need it to be ordered you can replace the outer std::map with a std::unordered_map. The lookup and insertion etc. is usually a bit quicker that way.

#include <unordered_map>
//...
std::unordered_map<int, std::map<std::pair<int, int>, int>> something{...};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading