I have a fixed number (5) of vectors of structs (structs are inserted at runtime, a number can vary).
And i have a enum class
which is used as a key for lookup. E.g.
enum class CountryCode {
kUS,
// ...other 4
};
const std::vector<SomeStruct>& get_by_country_code(CountryCode cc);
I can use std::unordered_map<CountryCode, std::vector<SomeStruct>, CustomHash>
with custom hash, but i think it not worth it for fixed size collection, which ordering is known before runtime.
What would be the most efficient way to store these 5 vectors and do a lookup by the enum
value?
I'm also thinking about std::tuple
but in my case values are not heterogeneous.
CodePudding user response:
What would be the most efficient way to store these 5 vectors and do a lookup by the enum value?
An array. The default values of enum are 0,1,... which fit perfectly as the indices of an array.
Only small hurdle is that enum classes must be explicitly converted to the underlying integer.
does array of vectors considered a good practice?
There's nothing particularly bad practice about them.
If the sizes of the vectors are known at the same time and they don't vary after creation, then there is a more efficient solution: Use a single vector that contains all objects partitioned by the country code. Then use an array of spans to the subvectors.
CodePudding user response:
#include <iostream>
#include <vector>
#include <cstdint>
#include <array>
using namespace std;
const int k_MAX_COUNTRY_CODE = 5;
enum class CountryCode: uint8_t {
COUNTRY_CODE_0 = 0,
COUNTRY_CODE_1 = 1,
COUNTRY_CODE_2 = 2,
COUNTRY_CODE_3 = 3,
COUNTRY_CODE_4 = 4,
};
void printVector(vector<int>& f_vec){
for(auto& el : f_vec){
cout << el << " ";
}
cout << "\n";
}
int main() {
CountryCode l_countryCode;
array<vector<int>, k_MAX_COUNTRY_CODE> l_lookUP;
vector<int> l_lookUP(k_MAX_COUNTRY_CODE);
for(int i = 0; i < k_MAX_COUNTRY_CODE; i ){
vector<int> tempVec((i 1)*2 , i 534);
l_lookUP[i] = tempVec;
}
printVector(l_lookUP[static_cast<int>(CountryCode::COUNTRY_CODE_4)]);
printVector(l_lookUP[static_cast<int>(CountryCode::COUNTRY_CODE_3)]);
printVector(l_lookUP[static_cast<int>(CountryCode::COUNTRY_CODE_1)]);
printVector(l_lookUP[static_cast<int>(CountryCode::COUNTRY_CODE_2)]);
return 0;
}
Like @eerorika suggested, I would also us an array for fast look up. I hope, this would be helpful.