加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 如何存储英文字典?

发布时间:2020-12-16 09:43:38 所属栏目:百科 来源:网络整理
导读:我正在写一个C程序,它读入英文字典(asc.order),而不是进一步处理. 在第一步中,我决定将所有内容读取到2D阵列. string dictionary[x][y]; 其中x仅为26,表示A-Z,y表示保存相对于x变量的单词. 但我无法预测y的大小,它是可变的,所以我不知道如何做到这一点. 其次
我正在写一个C程序,它读入英文字典(asc.order),而不是进一步处理.

在第一步中,我决定将所有内容读取到2D阵列.

string dictionary[x][y];

其中x仅为26,表示A-Z,y表示保存相对于x变量的单词.

但我无法预测y的大小,它是可变的,所以我不知道如何做到这一点.

其次,我听说过一个名为vector的容器.我如何使用vector来完成上述设计?例如,使用2D矢量,并使用第一个维度携带第一个字母,第二个维度携带单词?

解决方法

如果您的编译器支持某些c 11功能

#include <algorithm>
#include <iterator>
#include <string>
#include <vector>

int main()
{       
    std::vector<std::vector<std::string> > dictionary(26);
    //'a' part
    dictionary[0].push_back("alien");
    dictionary[0].push_back("amend");
    dictionary[0].push_back("apple");

    //.......
    //'z' part
    dictionary[25].push_back("zero");
    dictionary[25].push_back("zoo");

    //sort all of the words after insert
    for(auto &strs : dictionary){
        std::sort(std::begin(strs),std::end(strs));
    }

    //find the specific words of 'a'
    auto const it = std::equal_range(std::begin(dictionary[0]),std::end(dictionary[0]),"apple");
    if(it.first != it.second){
        std::cout<<*(it.first)<<std::endl;
    }else{
        std::cout<<"The word do not exist"<<std::endl;
    }           

    return 0;
}

如果没有,那么代码会变得有点单调乏味

#include <algorithm>
#include <string>
#include <vector>

int main()
{       
    std::vector<std::vector<std::string> > dictionary(26);
    //'a' part
    dictionary[0].push_back("alien");
    dictionary[0].push_back("amend");
    dictionary[0].push_back("apple");

    //.......
    //'z' part
    dictionary[25].push_back("zero");
    dictionary[25].push_back("zoo");            

    //you could use std::for_each if you like,I choose for loop because I
    //don't like to write so many trivial functor
    typedef std::vector<std::vector<std::string> >::size_type size_type;
    size_type const size = dictionary.size();
    for(size_type i = 0; i != size; ++i){
       std::sort(dictionary[i].begin(),dictionary[i].end());
    }

    //find the specific words of 'a'
    typedef std::vector<std::string>::const_iterator StrIter;
    std::pair<StrIter,StrIter> it = std::equal_range(dictionary[0].begin(),dictionary[0].end(),"apple");
    if(it.first != it.second){
        std::cout<<*(it.first)<<std::endl;
    }else{
        std::cout<<"The word do not exist"<<std::endl;
    }    

    return 0;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读