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.
还没有评论,来说两句吧...