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
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
CodePudding user response:
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{...};
CodePudding user response:
Try this
#include <iostream>
#include <map>
using namespace std;
int main()
{
map<int, map<int, map<int, int>>> something;
something[2001][1905][2000] = 500;
something[2001][1910][2030] = 700;
something[2005][2310][5930] = 599;
cout << "result: " << something[2001][1905][2000] << endl;
cout << "result: " << something[2001][1910][2030] << endl;
cout << "result: " << something[2005][2310][5930] << endl;
return 0;
}
CodePudding user response:
Use data-only structs or std::tuple
for that kind of thing:
Tuple example:
std::vector<std::tuple<int, int, int>> dataVectorName;
Struct example:
struct MyData
{
int a;
int b;
int c;
}
std::vector<MyData> dataVectorName;
I always use and recommend std::tuple
for data array. It's faster but does not look user-friendly. And to solve that problem, you can fake variables with typedef
or using
. And it's easy for nested datas.