【问题标题】:remove words of a text file from a map in C++ without loop在没有循环的情况下从 C++ 中的地图中删除文本文件的单词
【发布时间】:2016-02-29 00:55:21
【问题描述】:

我尝试创建一个集合来存储文本文件的某些单词。然后我想从我已经制作的地图中删除这些单词。我已经成功地制作了一组来存储这些单词,但我无法将它们从地图中删除。此外,我不能使用循环语句(如 for 循环或 while 循环)。

#include <iostream>
#include <iomanip>
#include <fstream>
#include <iterator>
#include <algorithm>
#include <vector>
#include <string>
#include <map>
#include <set>
#include <utility>
#include <sstream>
#include <list>

  ifstream stop_file( "remove_words.txt" );
  ofstream out( "output.txt" );

  set <string> S;

  copy(istream_iterator<string>(stop_file), 
       istream_iterator<string>(),
       inserter(S, begin(S)));

         //copy: copy from text file into a set

  remove_if(M.begin(), M.end(), S);

        //remove: function I try to remove words among words stored in a map
        //map I made up is all set, no need to worry

【问题讨论】:

    标签: c++ stl iostream fstream remove-if


    【解决方案1】:

    您能提供您的地图的声明吗?

    例如,如果地图是map&lt;string, int&gt;,你可以这样做:

    for (string & s : set)
    {
        map.erase(s);
    }
    

    使用 for_each 看起来像这样:

    std::for_each(set.begin(), set.end(), 
        [&map](const std::string & s) { map.erase(s); });
    

    另外,使用递归可以在没有循环的情况下进行删除

    template <typename Iter>
    void remove_map_elements(
        std::map<std::string, int> & map,
        Iter first,
        Iter last)
    {
        if (first == last || map.empty())
            return;
    
        map.erase(*first);
        remove_map_elements(map, ++first, last);
    }
    

    你喜欢的称呼

     remove_map_elements(map, set.begin(), set.end());
    

    【讨论】:

    • 它应该是const string&amp;,因为std::set::iterator 是一个常量迭代器。没有const,它不会编译。
    • 好的,谢谢。我的地图是 但我真的需要另一种方法来删除单词而无需编写 for 循环。不过,for_each 是适用的。
    • @Dorothy 为什么不能使用 for 循环?它必须在某个时候执行某种循环。此外,最有效的方法是要求您编写自己的 for 循环以考虑集合和映射的顺序。一个简单的解决方案将在每次擦除时执行完整的日志查找。
    • @NeilKirk 很抱歉我没有提到。实际上这是一个作业,我正在学习高级 C++ 循环,所以我不会。
    【解决方案2】:

    如果我理解正确,你需要这样的东西:

      std::map< std::string, int > m = {
        { "word1", 1 },
        { "word2", 2 },
        { "word3", 3 },
        { "word4", 4 }
      };
    
      std::set< std::string > wordsToRemove = { "word2" };
    
      std::for_each( 
        wordsToRemove.begin(), 
        wordsToRemove.end(), 
        [&m] ( const std::string& word )   
        { 
          m.erase( word );  
        } 
      );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-22
      • 1970-01-01
      • 1970-01-01
      • 2021-04-27
      • 2021-02-04
      • 2011-08-15
      相关资源
      最近更新 更多