C++11 成员和非成员begin、end( 标准库与标准库容器成员函数)

C++ Primer,这两点分别在P106、P298。如果需要详细理解最好去书中查看详细解释和示例代码

标准库的begin()和end()函数是C++11新标准引入的函数,可以对数组类型进行操作,返回其首尾指针,对标准库容器操作,返回相应迭代器。
标准库容器的begin()和end()成员函数属于对应类的成员,返回的是对象容器的首尾迭代器。

新标准库的begin()和end()函数可以让我们更容易的获取数组的首尾指针(注意尾指针是最后一个元素的下一个地址)

最简单的冒泡排序例子:

//
//  main.cpp
//  成员/非成员begin,end
//
//  Created by yulei on 2018/7/17.
//  Copyright © 2018 yulei. All rights reserved.
//

#include <iostream>
#include <vector>
using namespace std;
//传入首尾指针
void Bubble_sort(int *begin, int *end) {
    for (auto p1 = begin; p1 != end; ++p1) {
        for (auto p2 = begin; p2 != end - 1; ++p2) {
            if (*p2 > *(p2 + 1)) {
                int val_temp = *p2;
                *p2 = *(p2 + 1);
                *(p2 + 1) = val_temp;
            }
        }
    }
}
//对函数进行重载,传入一对迭代器,同时进行第一次改进
void Bubble_sort(vector<int>::iterator begin, vector<int>::iterator end) {
    int flag = 0;
    for (auto p1 = begin; p1 != end; ++p1) {
        flag = 0;
        for (auto p2 = begin; p2 != end - 1; ++p2) {
            if (*p2 > *(p2 + 1)) {
                int val_temp = *p2;
                *p2 = *(p2 + 1);
                *(p2 + 1) = val_temp;
                flag = 1; //表示此轮循环进行了交换
            }
        }
        if (flag == 0) //上一轮循环中未进行交换,直接跳出
        {
            break;
        }
    }
}
int main(int argc, const char *argv[]) {
    int a[10] = {1, 5, 8, 7, 9, 6, 4, 3, 2, 0};
    vector<int> vec(a, a + 10);
    Bubble_sort(begin(a), end(a)); //标准库的begin()和end()函数
    cout << "内置数组冒泡排序后:";
    for (int i = 0; i < 10; ++i) {
        cout << a[i] << " ";
    }

    Bubble_sort(vec.begin(), vec.end()); //标准库容器的begin()和end()成员函数
    cout<<endl;
    cout<<"vector冒泡排序后:";
    for (int i = 0; i < 10; ++i)
    {
        cout<<vec[i]<<" ";
    }
    
    cin.get();
    return 0;
}

顺带一说,cbegin()和cend(),c++ primer中说到,cbengin/cend是返回对象是const(常量)类型迭代器。在没有修改容器内容

需求前提下,使用cbegin/cend

cbegin(cend):

Return const_iterator to beginning

Returns a const_iterator pointing to the first element in the container.

 

begin(end):

Return iterator to beginning

Returns an iterator pointing to the first character of the string.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值