【C++ 查表】
在C++中,“查表”通常指的是使用数组或 map、vector 等数据结构来存储数据,并通过索引或键值进行 O(1) 时间复杂度的访问。
【示例代码】
#include <iostream>
#include <vector>
#include <map>
#include <unordered_map>
using namespace std;
int main() {
int iArray[]= {6,9,7,1,5,4,3,8,2};
int index=3;
cout<<"Element at index "<<index<<" is "<<iArray[index]<<endl;
vector<int> iVector= {6,9,7,1,5,4,3,8,2};
index=7;
cout<<"Element at index "<<index<<" is "<<iVector[index]<<endl;
map<int,char> iMap= {{3,'a'},{6,'b'},{9,'c'},{8,'d'},{5,'e'}};
int key=6;
cout<<"Element with key "<<key<<" is "<<iMap[key]<<endl;
unordered_map<int,char> iUnMap= {{5,'a'},{8,'f'},{7,'c'}};
key=8;
cout<<"Element with key "<<key<<" is "<<iUnMap[key]<<endl;
return 0;
}
/*
Element at index 3 is 1
Element at index 7 is 8
Element with key 6 is b
Element with key 8 is f
*/