c++ unordered_set 学习笔记1

来源: unordered_set - C++ Reference

无序存储不同的元素,支持基于值的检索。

值value就是key,规定了每一个元素的唯一性。key不可改变。

unorder_set中排列元素是无序的,但是存储是依靠哈希值,支持基于值的快速检索。

一、constructs

注意:range constructs [first,end)

// constructing unordered_sets
#include <iostream>
#include <string>
#include <unordered_set>

template<class T>
T cmerge (T a, T b) { T t(a); t.insert(b.begin(),b.end()); return t; }

int main ()
{
  std::unordered_set<std::string> first;                                // empty
  std::unordered_set<std::string> second ( {"red","green","blue"} );    // init list
  std::unordered_set<std::string> third ( {"orange","pink","yellow"} ); // init list
  std::unordered_set<std::string> fourth ( second );                    // copy
  std::unordered_set<std::string> fifth ( cmerge(third,fourth) );       // move
  std::unordered_set<std::string> sixth ( fifth.begin(), fifth.end() ); // range

  std::cout << "sixth contains:";
  for (const std::string& x: sixth) std::cout << " " << x;
  std::cout << std::endl;

  return 0;
}

运行结果

 二、Capacity

1,empty() 判空

2.size()长度

2.max_size()最大值

三、Iterators

begin()

end()

四、element lookup

1.find()

iterator find ( const key_type& k );

搜索容器中值为k的元素,如果找到返回指向该元素的iterator;

如果不在容器中,返回end

// unordered_set::find
#include <iostream>
#include <string>
#include <unordered_set>

int main ()
{
  std::unordered_set<std::string> myset = { "red","green","blue" };

  std::string input;
  std::cout << "color? ";
  getline (std::cin,input);

  std::unordered_set<std::string>::const_iterator got = myset.find (input);

  if ( got == myset.end() )
    std::cout << "not found in myset";
  else
    std::cout << *got << " is in myset";


  std::cout << std::endl;

  return 0;
}

运行结果:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值