C++关联容器

来源:互联网 发布:java三大程序结构 编辑:程序博客网 时间:2024/06/04 23:25

摘要:

关联容器中的元素是按关键字来保存和访问的。两个主要的关联容器:map,set。头文件map,set。

关联容器类型 描述 map set multimap multiset 无序集合 unordered_map unordered_set unordered_multimap unordered_multiset

1、简单的例子

#include <iostream>#include <map>#include <string>using namespace std;int main(){    map<string,size_t> word_count;    string word;    while(cin >> word){        ++word_count[word];    }    map<string,size_t>::iterator w;    for(w = word_count.begin();w!= word_count.end();w++)    {        cout<<(*w).first<<"occurs<<(*w).second<<(((*w).second>1)? "times":"time")<<endl;    }    return 0;}
map<string,size_t> word_count;string arr[] = {"hehe","haha","heihei"};size_t size = sizeof(arr)/sizeof(string);cout << size << endl;set<string> words(arr,arr+size);string word;while(cin >> word){    if(words.find(word) == words.end()){        ++word_count[word];        cout << word_count[word] <<endl;    }}

2、pair类型

定义在utility头文件中
一个pair保存两个数据成员。

pair<string,string> strstr;//pair的默认构造函数对数据成员进行值初始化,因此strstr保存一个包含两个空string的pair
#include <utility>#include <iostream>#include <string>using namespace std;int main(){    pair<int,int> pint(2,12);    pair<string,string> pstr("Jack","Tom");    cout<<pint.first<<pint.second<<endl;    cout<<pstr.first<<pstr.second<<endl;    return 0;}

pair操作

#include <iostream>#include <utility>#include <string>using namespace std;int main(){    pair<int, string> p1, p2;    p1 = make_pair(2, "Jack"); //    p2.swap(p1);    cout << "(" << p2.first << ", " << p2.second << ")\n";}

3、关联容器操作

3.1、类型

类型 描述 key_type 关键字类型 value_type map->pair,set->key_ype mapped_type 关键字关联的类型

3.2、关联容器迭代器

//mapmap<string,int>mm;pair<string,int>mp("yang",100);mm.insert(mp);map<string,int>::iterator miter;miter = mm.begin();string name = miter->first;cout << name;miter->first = "Yang"; //关键字是const类型,不能改变cout << miter->first

对map而言first成员保存const关键字,second成员保存值

set的迭代器是const的

set<string>ms;ms.insert("heihei");cout << *ms.begin();

遍历关联容器

map<int,int>mmap;map<int,int>::iterator miter = mmap.cbegin();while(miter!=mmap.cend()){    cout<<miter->first<<miter->second<<endl;    ++miter;    }

关联容器和算法
我们通常不对关联容器使用泛型算法
例如泛型find会进行顺序搜索,比关联容器定义的专用find效率低。

3.3、添加元素

int arr[] = {1,2,3,4,5,6};size_t size = sizeof(arr)/sizeof(int);vector<int> vec(arr,arr+size);set<int> mset;mset.insert(vec.begin(),vec.end()); //

3.4、删除元素

c.erase();

3.5、map的下标操作
map提供了下标运算符,和at函数,而set不支持下标。
与其他的下标运算不同的时,如果关键字不再map中,会为它创建一个元素并插入到map中。
对map进行下标操作时,会返回mapped_type对象,但当解引用一个map迭代器时,会得到一个value_type对象。

3.6、访问元素
find(),count()

4、无序容器

无序容器管理操作 描述 桶接口 c.bucket_count() 正在使用的桶的个数 c.max_bucket_count() 容器能容纳的最多的桶的个数 c.bucket_size(n) 第n个桶有多少个元素 桶迭代 local_iterator 可以用来访问桶中元素的迭代器 const_local_iterator 桶迭代器的const版本 c.begin(n),c.end(n) 桶n的首元素迭代器和尾迭代器 c.cbegin(n),c.cend(n) const版 哈希策略 c.load_factor() 每个桶的平均元素数量,返回float值 c.max_load_factor() c试图维护的平均桶大小 c.rehash(n) 重组存储 c.reserve(n) 重组存储
0 0
原创粉丝点击