接上文:
要求是创建索引结构(如B+树)实现快速搜索,不过我不会。。。
这里只存储了一个带位置的索引文件以供后续检索。
数据结构:
/* data */
int64_t id; //数据的ID
int64_t property[PRO_NUM]; //数据的100个属性
int file_len; //文件总长度
vector<int> fast_search; //对哪些属性创建了索引文件。存成变量下次用就不得行,所以可以写个存成文件的一劳永逸,但是我懒得写。就这样吧。
寻找哪些行的某个属性有在范围内:
分为:有索引文件可供查找和无索引文件查找两种情况。
有索引文件则读取索引文件中存储的相对位置,通过相对位置查找。
无索引文件查找则见上文,且在查找结束后创建索引文件。
vector<int> FindData(int property_num, int64_t min, int64_t max){
vector<int> row;
vector<int> ret_row; //创建需要返回的行向量vector
//打开本地的表文件
ifstream infile;
infile.open("data_storage.txt", ios::in); //打开模式
//找到索引时
for(int i = 0; i < fast_search.size(); i++){
if(property_num == fast_search[i]){
vector<int> index_vec = SearchIndex(property_num);
return FindWithIndex(index_vec, min, max);
}
}
//没找到索引时
int64_t number;
//将txt中的数据存入row中
while(infile >> number){
row.push_back(number);
}
cout << "row.size: " << row.size() << endl;
file_len = row.size();
//判断row中符合要求的行,放入ret_row
for(int i = property_num; i < row.size(); i = i + PRO_NUM + 1){
if(row[i] >= min && row[i] <= max){
ret_row.push_back(1 + i / (PRO_NUM + 1));
}
}
//顺便为该属性创建一个索引文件
CreateIndex(property_num);
return ret_row;
}
创建索引文件:
创建索引文件的名字为(第几个属性)_index.txt。
bool CreateIndex(int property_num){
//创建索引文件XX_index.txt
ofstream outfile;
string toStrPro = to_string(property_num);
outfile.open(toStrPro + "_index.txt", ios::binary | ios::app | ios::in | ios::out);
//打开文件出错判断
if(!outfile){
cout << "Open file error" << endl;
return false;
}
//存储索引文件
for(int i = property_num; i < file_len; i = i + PRO_NUM + 1){
outfile << i << "\n";
}
fast_search.push_back(property_num);
return true;
}
查询索引文件中存储的位置并返回:
vector<int> SearchIndex(int property_num){
//检索索引文件XX_index.txt
ifstream infile;
vector<int> index_vec; //位置
string toStrPro = to_string(property_num);
infile.open(toStrPro + "_index.txt", ios::in); //打开模式
//打开文件出错判断
if(!infile){
cout << "Open file error" << endl;
return index_vec;
}
int number;
//将txt中的数字存入index_vec中
while(infile >> number){
index_vec.push_back(number);
}
return index_vec;
}
通过位置找符合要求的那些行:
vector<int> FindWithIndex(vector<int> index_vec, int64_t min, int64_t max){
cout << "Find with Index" << endl;
//检索索引文件XX_index.txt
ifstream infile;
vector<int> ret_row; //位置
int64_t number;
int count = 0, i = 0;
infile.open("data_storage.txt", ios::in); //打开模式
while(infile >> number){
if(count == index_vec[i]){
// cout << "count: " << count << endl;
// cout << "index vec: " << index_vec[i] << endl;
// cout << "number: " << number << endl;
// cout << "\n";
if(number >= min && number <= max){
ret_row.push_back(i+1);
}
i++;
}
count++;
}
return ret_row;
}
随便放几个属性测试一下50-100。对的。