[英]remove words of a text file from a map in C++ without loop
我嘗試進行設置以存儲文本文件的某些單詞。 然后,我想從已經組成的地圖中刪除這些單詞。 我已經成功建立了一個存儲這些單詞的集合,但是我無法從地圖上將其刪除。 此外,我不能使用循環語句(如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
您能提供地圖聲明嗎?
例如,如果地圖是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());
如果我正確理解,則需要這樣的內容:
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 );
}
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.