【问题标题】:how to search all map keys c++如何搜索所有地图键c ++
【发布时间】:2018-08-23 15:37:04
【问题描述】:

我要实现的是一个基本的拼写检查器,它读取输入文本文件并将单词与一个小字典进行比较。如果该词不在字典中,则假定它拼写错误,然后提示用户正确拼写该词。这个拼写正确的单词与拼写错误的对应词一起存储在地图中。到目前为止,我已经能够做到这一切。我无法弄清楚的是如何遍历整个地图以检查该键(拼写错误的单词)是否已经存在,而无需每次都询问用户如果在地图的该迭代中找不到它如何拼写它?下面是我目前拥有的代码,它检查单词是否在字典中,如果不是,询问用户如何拼写,并将其添加到地图中。

std::map<std::string,std::string>::iterator p = m_Replacements.begin();
            bool isIn = m_Dictionary.find(oneWord) != m_Dictionary.end();
            std::map<std::string,std::string>::iterator found = m_Replacements.find(oneWord);

            if(found==m_Replacements.end())
            {
                if( isIn == false)
                {
                    osInputPrompt<<"How do you correctly spell " + oneWord + "\n";
                    isInputPrompt >> correctSpell;
                    m_Replacements.insert(make_pair(textWord,correctSpell));
                    osOutput<<correctSpell + " ";
                }
                else
                {
                    osOutput<<oneWord + " ";
                }

总而言之,我想在循环中添加另一个循环,检查单词是否在字典中,然后检查整个地图以查看拼写错误的单词是否已经存在而不询问“你如何正确拼写...”对于地图循环的每次迭代。只是为了澄清,我不是在问如何迭代地图,我已经知道如何做到这一点。提前致谢。

【问题讨论】:

  • While iterator!=end?
  • 声音接近你想要的吗?
  • 首先你说我不知道如何迭代整个地图 -- 然后 -- 我不是在问如何迭代地图,我已经知道该怎么做了。不清楚你在问什么。另外,textWord 是什么?
  • 感谢所有回复

标签: c++ loops dictionary iterator


【解决方案1】:
std::map<std::string,std::string>::iterator p;
std::string found;
for(p = m_repl.begin(); p != m_repl.end(); ++p)
{
     if(p->second == <what I am looking for>)
      {
         found = p->second;
         break;
     }
}

ie 循环遍历整个字典。更新的 c++ 版本具有更好的枚举语法 - 请参阅 How to use range-based for() loop with std::map?

【讨论】:

    【解决方案2】:

    陷入了我正在做的事情,但我只是通过添加一个像这样的布尔值来避免询问用户循环的每次迭代

    bool mapFound;
                        for(std::map<std::string,std::string>::iterator it = m_Replacements.begin(); it!= m_Replacements.end(); it++)
                        {
                            std::string word = it->first;
                            if(word == oneWord)
                            {
                                mapFound = true;
                            }
                        }
    

    【讨论】:

      猜你喜欢
      • 2017-07-17
      • 1970-01-01
      • 1970-01-01
      • 2016-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-25
      • 1970-01-01
      相关资源
      最近更新 更多