c++關聯容器map,set

一、map

1.map是關鍵字-值對的集合,也被成爲關聯數組,

2.定義map:

map<string, size_t> imap;

初始化map:map<string, string> imap = {{"abc", "bcd"}, {"def","hjk"}};

3.使用map例子(統計txt文檔中某個單詞對應的行數):

#include<iostream>

#include<map>

#include<vector>

#include<fstream>

using namespace std;

int main()

{

map<string, vector<int>> word;

ifstream in("11.txt");

string line;

int lineNum = 0;

while(getline(in, line))

{

lineNum ++;

word[line].push_back(lineNum);

}

for(auto w:word)

{

for(auto c:w.second)

cout << w.first << " " << c << endl;

}

return 0;

}

 

二、set

1.set是關鍵字的簡單組合,當只想知道一個值是否存在時,set是最有用的。

2.下面舉一個例子來說明set。該例子的作用是忽略標點和某些單詞來統計單詞個數

#include<iostream>

#include<cctype>

#include<string>

#include<set>

using namespace std;

int main()

{

map<string, size_t> count_word;

set<string> sset = {"but","the","and","or","an","a"};

string word;

char *ch;

int cnt = 0;

auto punct_iter = word.begin();

while(cin >> word)

{

ch = new char[word.size()];

if(sset.find(word) == sset.end())                      //未找到find會返回尾置迭代器

{

for(auto it = word.begin(); it != word.end(); it++)

{

if(ispunct(*it))

continue;

else

{

*it = tolower(*it);

ch[cnt] = *it;

cnt ++;

}

}

ch[cnt] = '\0' ;

++count_word[ch] ;

}

cnt = 0;

delete[] ch;

}

for(auto w:count_word)

cout << w.first << " occures " << w.second << ((w.second  > 1) ? " times" : " time") << endl;

return 0;

}

 

三、關鍵字類型的要求

1. 關鍵字必須定義元素的比較方法,默認情況下,標準庫使用關鍵字類型的<運算符來比較兩個關鍵字。

2. 可以向一個算法提供我們自己定義的比較操作。

比如:

bool  CompareStr(string str1, string str2)

{

return str1[0] < str2[0];

}

set<string, decltype(CompareStr)*>              //當用decltype來獲得一個函數指針類型時,必須加上一個*來指出我們使用一個給定函數類型的指針

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章