# C++ 数据结构实战：快速查找

给定m个商品ID, 4个特征(特征数量可增可减)，已知商品对应的每个特征的值，如何快速获取某个商品的某个特征值？

std::unordered_map<int64_t, float> FeatureKeyV;
std::vector<FeatureKeyV*> FeatureKeyValueVec;

/**
* 给定m个商品ID, 4个特征(特征数量可增可减)，已知商品对应的每个特征的值，如何快速获取某个商品的某个特征值？
*/
#include <iostream>
#include<unordered_map>

enum {
FEATURE_IREM_NUM_1=0,
FEATURE_IREM_NUM_2,
FEATURE_IREM_NUM_3,
FEATURE_IREM_NUM_4,
FEATURE_TOTAL_NUM
};
typedef std::unordered_map<int64_t, float> FeatureKeyV;
typedef std::vector<FeatureKeyV*> FeatureKeyValueVec;
FeatureKeyValueVec features;

static const size_t NUM_DOC_ROW_NUM = 750;

void Init()
{
features.resize(FEATURE_TOTAL_NUM);
for(size_t i = 0; i < features.size(); i++) {
FeatureKeyV* &f = features[i];
f = new FeatureKeyV(NUM_DOC_ROW_NUM);
}
}
void SetFeature(int64_t sku, int fid, float value)
{
if(fid > FEATURE_IREM_NUM_4 or fid < FEATURE_IREM_NUM_1)
return;
int i = fid - FEATURE_IREM_NUM_1;
if(features[i])
(*(features[i]))[sku] = value;
}
int GetFeature(int64_t sku, int fid, float &value)
{
if(fid > FEATURE_IREM_NUM_4 or fid < FEATURE_IREM_NUM_1)
return -1;
int i = fid - FEATURE_IREM_NUM_1;
if(features[i])
{
FeatureKeyV::iterator it = features[i]->find(sku);
if (it == features[i]->end())
return -1;
value = it->second;
return 0;
}
return -1;
}
void Reset()
{
for(size_t i = 0; i < features.size(); i++)
{
if(features[i])
{
features[i]->clear();
delete features[i];
}
}
}
int main()
{
Init();

int64_t sku1 = 10000;
SetFeature(sku1,FEATURE_IREM_NUM_1,20);
SetFeature(sku1,FEATURE_IREM_NUM_2,30);
SetFeature(sku1,FEATURE_IREM_NUM_3,40);
SetFeature(sku1,FEATURE_IREM_NUM_4,50);
int64_t sku2 = 10001;
SetFeature(sku2,FEATURE_IREM_NUM_1,22);
SetFeature(sku2,FEATURE_IREM_NUM_2,33);
SetFeature(sku2,FEATURE_IREM_NUM_3,44);
SetFeature(sku2,FEATURE_IREM_NUM_4,55);

float value;
if (!GetFeature(sku2, FEATURE_IREM_NUM_1, value))
{
cout << "feature:" << value << endl;
}

Reset();
}