我想做一个字典程序,我的字典是成对实现的。我想在我的数组中搜索一个术语并使用 STL 函数返回所有这些的描述。我做了这个:
#include<iostream>
#include<fstream>
#include<algorithm>
#include<string.h>
using namespace std;
bool compare(pair<string,string>a,pair<string,string>b) {
return a.first<b.first;
}
int main() {
pair<string,string> a[100]=pair<string,string>();
int dimension=0;
ifstream f("dictionar.in");
string name,description;
while(f>>name) {
getline(f,description);
a[dimension]=make_pair(name,description);
dimension++;
}
for(int i=0;i<dimension;i++)
cout<<a[i].first<<" "<<a[i].second<<endl;
sort(a,a+dimension,compare);
cout<<endl;
for(int i=0;i<dimension;i++)
cout<<a[i].first<<" "<<a[i].second<<endl;
string searchelem;
cin>>searchelem;
}
我想使用“searchelement”来查找 pair 数组中是否存在与 searchelement 相等的元素,如果存在则返回索引。我应该使用什么功能?
最佳答案
使用std::map
。映射通常称为关联数组 或字典。
您可能希望分解键和值并使用trie 数据结构。 trie 允许更有效的查找(按字长)。
关于c++ - STL 对和二进制搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38485448/