c++ - STL 对和二进制搜索

标签 c++ stl

我想做一个字典程序,我的字典是成对实现的。我想在我的数组中搜索一个术语并使用 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/

相关文章:

c++ - "detail"和 "impl"文件夹有什么用?

c++ - nullptr 的运算符 <<(流输出)

c++ - 为什么 std::map::insert 不能采用键和值而不是 std::pair?

c++11 - std::thread::id 跨进程是否唯一?

c++ - 使用 C++ 和 sfml 的简单碰撞问题

c++ - 什么时候在 C++11 lambda 的定义中需要明确命名的变量捕获?

c++ - 检测 IBeam 光标

c++ - 函数不写入 txt 文件

c++ - 如何获得大对齐的 block ?

c++ - C++ 映射可以包含指向我的任意类的指针吗?