[英]C++ count and map
我正在計算每個單詞在文本文件中出現的次數。 我想避免出現案件,因此正在降低我的意見,然后進行計數。 我有一個具有字符串和整數的map數據結構,以保持計數。 現在,當我輸出單詞及其數量時,我不希望單詞使用小寫字母,而是希望它保持其原始大小寫。 因此,為了計數,所有單詞應更改為小寫,但在輸出時,所有單詞均應保持原始大小寫。 無論如何,僅使用一張地圖即可實現這一目標?
std::map
的第三個模板參數是比較器類型。 您可以提供自己的比較操作,在這種情況下不區分大小寫。
struct CaseInsensitive {
bool operator()(std::string const& left, std::string const& right) const {
size_t const size = std::min(left.size(), right.size());
for (size_t i = 0; i != size; ++i) {
char const lowerLeft = std::tolower(left[i]);
char const lowerRight = std::tolower(right[i]);
if (lowerLeft < lowerRight) { return true; }
if (lowerLeft > lowerRight) { return false; }
// if equal? continue!
}
// same prefix? then we compare the length
return left.size() < right.size();
}
};
然后實例化您的地圖:
typedef std::map<std::string, unsigned, CaseInsensitive> MyWordCountingMap;
注意:僅保留第一個拼寫(對您來說還可以)
這應該工作。 對於多種情況,第一種情況將位於地圖內,而不是小寫。 此外,該解決方案僅使用您想要的一張地圖
using namespace std;
struct StrCaseInsensitive
{
bool operator() (const string& left , const string& right )
{
return _stricmp( left.c_str() , right.c_str() ) < 0;
}
};
int main(void)
{
char* input[] = { "Foo" , "bar" , "Bar" , "FOO" };
std::map<string, int , StrCaseInsensitive> CountMap;
for( int i = 0 ; i < 4; ++i )
{
CountMap[ input[i] ] += 1;
}
return 0;
}
您可以使用map<string, vector<string> >
。
關鍵是小寫單詞。 該值是該單詞所有給定情況的向量。
(您也可以使用基本相同的multimap<string, string>
,但是我通常更喜歡矢量地圖)
map<string, vector<string> > m;
m.size(); // number of lowercase words
m["abc"].size(); // number of the given cases of the word "abc"
您想在同一單詞的不同大小寫變體中發生什么?
一種可能是將std :: multiset與無大小寫比較器用作其Compare
模板參數。 在這種情況下,每個單詞的所有變體都將保留在集合中。 每個單詞出現的次數可以通過集合的count()成員函數獲得。
您可以使用結構或std::pair
保留原始大小寫和多次出現。 然后,您的類型將如下所示: map < string, pair <string, int> >
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.