2

我尝试制作一组​​来存储文本文件的某些单词。然后我想从我已经制作的地图中删除这些单词。我已经成功地制作了一组来存储这些单词,但我无法将它们从地图中删除。此外,我不能使用循环语句(如 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
4

2 回答 2

0

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

例如,如果地图是,map<string, int>您可以执行以下操作:

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());
于 2015-11-26T03:29:08.390 回答
0

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

  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 );  
    } 
  );
于 2015-11-26T10:14:01.923 回答