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

╰+哭是因爲堅強的太久メ 2022-05-20 10:40 225阅读 0赞

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

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

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

最简单的冒泡排序例子:

  1. //
  2. // main.cpp
  3. // 成员/非成员begin,end
  4. //
  5. // Created by yulei on 2018/7/17.
  6. // Copyright © 2018 yulei. All rights reserved.
  7. //
  8. #include <iostream>
  9. #include <vector>
  10. using namespace std;
  11. //传入首尾指针
  12. void Bubble_sort(int *begin, int *end) {
  13. for (auto p1 = begin; p1 != end; ++p1) {
  14. for (auto p2 = begin; p2 != end - 1; ++p2) {
  15. if (*p2 > *(p2 + 1)) {
  16. int val_temp = *p2;
  17. *p2 = *(p2 + 1);
  18. *(p2 + 1) = val_temp;
  19. }
  20. }
  21. }
  22. }
  23. //对函数进行重载,传入一对迭代器,同时进行第一次改进
  24. void Bubble_sort(vector<int>::iterator begin, vector<int>::iterator end) {
  25. int flag = 0;
  26. for (auto p1 = begin; p1 != end; ++p1) {
  27. flag = 0;
  28. for (auto p2 = begin; p2 != end - 1; ++p2) {
  29. if (*p2 > *(p2 + 1)) {
  30. int val_temp = *p2;
  31. *p2 = *(p2 + 1);
  32. *(p2 + 1) = val_temp;
  33. flag = 1; //表示此轮循环进行了交换
  34. }
  35. }
  36. if (flag == 0) //上一轮循环中未进行交换,直接跳出
  37. {
  38. break;
  39. }
  40. }
  41. }
  42. int main(int argc, const char *argv[]) {
  43. int a[10] = {1, 5, 8, 7, 9, 6, 4, 3, 2, 0};
  44. vector<int> vec(a, a + 10);
  45. Bubble_sort(begin(a), end(a)); //标准库的begin()和end()函数
  46. cout << "内置数组冒泡排序后:";
  47. for (int i = 0; i < 10; ++i) {
  48. cout << a[i] << " ";
  49. }
  50. Bubble_sort(vec.begin(), vec.end()); //标准库容器的begin()和end()成员函数
  51. cout<<endl;
  52. cout<<"vector冒泡排序后:";
  53. for (int i = 0; i < 10; ++i)
  54. {
  55. cout<<vec[i]<<" ";
  56. }
  57. cin.get();
  58. return 0;
  59. }

顺带一说,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.

发表评论

表情:
评论列表 (有 0 条评论,225人围观)

还没有评论,来说两句吧...

相关阅读