STL——map和set

一、map

1、map被定义为一对(pair即key和value)数值。

    key值在map内最多只有一份。

     假如需要对一篇文章中的单词计数,那么就可以建立一个map,string类型的key,int型的value,表示某个单词出现的次数。

    #include<map>
    #include<string>
    map<string,int> words;

    输入key/value的方式如下:

words["hello"] = 1;

    字数统计程序:

string word;
while(cin >> word)
{
    words[word]++;
}

    key和value对应于map对象内名为first和second的member。循环打印map内的key/value值时可以如下操作:

map<string,int>::iterator iter = words.begin();
for(;iter != words.end();iter++)
{
	cout << "key:" << iter->first <<
		"value:" << iter->second << endl;
}

2、查询map内是否存在某个key

//三种方法:

//No1
int count = 0;
if(!words["hello"])
	//hello不存在
//No2
if(words.find("hello") == words.end())
	//hello不存在
//No3
if(!words.count("hello"))
	//hello不存在

    第一种方法:如果“hello”不存在,那么会自动加入map中,key为“hello”,value为对应类型的默认值;

    第二种方法:find函数为map对象的成员函数,不是泛型算法的函数。函数返回值为指向一个pair的迭代器,如果不存在则为end()。

    第三种方法:count函数返回的为某个特定项目在map对象内的个数

二、set

1、set由一群key的组合而成,没有value。

    set中的key也只有一份。

    假如我们统计一篇文章中出现了哪些单词,而不必统计出现的次数,那么就可以用set容器来存储出现过得单词。

#include<set>
#include<string>
set<string> words;

    向words中加入元素使用insert函数

words.insert(ival); //加入单一元素
words.insert(vec.begin(), vec.end());  //加入一个范围元素,vec为vector容器

    查询某值是否在set中

words.count("hello"); //返回hello的份数

    


猜你喜欢

转载自blog.csdn.net/fangyan5218/article/details/80141802