关联容器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来获得一个函数指针类型时,必须加上一个*来指出我们使用一个给定函数类型的指针

猜你喜欢

转载自blog.csdn.net/kuangbao9/article/details/77993667