【C++】std::unordered_map容器

简述:

对于map,其内部数据结构为红黑树,因此所有元素插入到map里面都会排好序,而且搜索过程为平衡二叉树搜索,因此时间复杂度为O(logN)。我们知道还有一种快速的搜索方法,那边是哈希(又名散列),利用哈希函数,通过哈希值能快速的查找到所需元素。unordered_map便是采用这种数据结构实现,其为无序映射,unordered _map与map的使用基本一样,都是key/value之间的映射,只是他们内部采用的数据结构不一样,由于unordered_map内部是用散列表来实现快速查找,因此其内部元素完全是一种无序状态。哈希表利用哈希函数,将关键字的哈希值放都一个桶(bucket)里面,具有相同哈希值的放入到同一个桶。

头文件:

#include

1、构造函数

typedef std::unordered_map stringmap;

stringmap first;                              // empty
stringmap second ( { {"apple","red"},{"lemon","yellow"}} );       // init list
stringmap third ( { {"orange","orange"},{"strawberry","red"}} );  // init list
stringmap fourth (second);                    // copy
stringmap fifth (merge(third,fourth));        // move
stringmap sixth (fifth.begin(),fifth.end());  // range

2、容器大小

stringmap second ( { {"apple","red"},{"lemon","yellow"}} );       // init list

cout << second.empty() << endl;
cout << second.size() << endl;

3、获取元素

cout << second[0] << endl; cout << seco
pair::iterator, bool> ret;
ret = unorderedFirst.insert(pair('a', 10));

if (ret.second)
{
    cout << "insert succeed.." << endl;
}
else
{
    cout << "insert failed.." << endl;
}
unordered_map second;
second['a'] = 1;
second['b'] = 2;
second['c'] = 3;

//删除元素
second.erase ( second.begin() );      // erasing by iterator
second.erase ('a');             // erasing by key
second.erase ( second.find('c'), second.end() ); // erasing by range


second.clear();  //清空
second.swap(first);   //互换

cout << second.bucket_count() << endl;  //返回桶的数量

cout << second.bucket_size() << endl;  //返回每个桶的大小

cout << second.bucket('a') << endl; //返回当前元素在哪个桶

unorderedFirst.rehash(10);   //设置桶的数量

4、查找元素

unordered_map::iterator it;
it = unorderedFirst.find('a');   //返回查找到元素的iterator,如未查找到,返回end()

if (it != unorderedFirst.end())
{
    cout << (*it).first << " " << (*it).second << endl;
}

int n;
n = unorderedFirst.count('z');  //测试某个关键字是否存在

cout << n << endl;

5、修改元素

pair::iterator, bool> ret;
ret = unorderedFirst.insert(pair('a', 10));

if (ret.second)
{
    cout << "insert succeed.." << endl;
}
else
{
    cout << "insert failed.." << endl;
}

unordered_map second;
second['a'] = 1;
second['b'] = 2;
second['c'] = 3;

//删除元素
second.erase ( second.begin() );      // erasing by iterator
second.erase ('a');             // erasing by key
second.erase ( second.find('c'), second.end() ); // erasing by range
second.clear();  //清空
second.swap(first);   //互换
cout << second.bucket_count() << endl;  //返回桶的数量
cout << second.bucket_size() << endl;  //返回每个桶的大小
cout << second.bucket('a') << endl; //返回当前元素在哪个桶
unorderedFirst.rehash(10);   //设置桶的数量

 

你可能感兴趣的:(c/c++)