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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kuangbao9

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值