unordered_set学习之迭代器操作begin,cbegin(C++11),end,cend(C++11)

本篇学习unordered_set的迭代器操作,具体函数如下:

begin cbegin

(C++11)

返回指向起始的迭代器
(公开成员函数)

end cend

(C++11)

返回指向末尾的迭代器
(公开成员函数)
#include <unordered_set>
#include <iostream>
#include <string>

using namespace std;

void iteratorOperator()
{
    unordered_set<int> set1 = {5,8,4,2};
    cout << "set1.size = " << set1.size() << " set1.empty = " << set1.empty() << " set1.max_size = " << set1.max_size() << endl;
    cout << "set1 of value:" << endl;
    for(auto &val: set1)
    {
        cout << val << "\t";
    }
    cout << endl;
    //1.begin 返回指向起始的迭代器
    unordered_set<int>::iterator iter1 = set1.begin();
    cout << "set1.begin => " << *iter1 << endl;
    //*iter1 = 55;
    //注:不能通过unordered_set的迭代器去修改unordered_set元素,原因是修改元素会破坏unordered_set组织,所以其实begin和cbegin是一样的效果

    //2.cbegin 返回指向起始的常量迭代器,不能通过迭代器修改值a
    unordered_set<int>::const_iterator iter2 = set1.cbegin();
    cout << "set1.cbegin => " << *iter2 << endl;
    //*iter2 = 85;//不可以修改值

    //3.end 返回指向末尾的迭代器,即最后一元素的下一个位置,可以通过迭代器修改它的值
    unordered_set<int>::iterator iter3 = set1.end();
    --iter3;//指向最后一个元素
    cout << "set1.end => " << *iter3 << endl;

    //4.cend 返回指向末尾的迭代器,即最后一元素的下一个位置,不能通过迭代器修改它的值
    unordered_set<int>::const_iterator iter4 = set1.cend();
    --iter4;//指向最后一个元素
    cout << "set1.cend => " << *iter4 << endl;
    //*iter4 = 37;//不可以修改值
}

int main()
{
    iteratorOperator();

    cout << "Hello, world!" << endl;
    return 0;
}

运行结果:

 

参考:

https://zh.cppreference.com/w/cpp/container/unordered_set

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值