迭代器
int arr[5]{1,2,3,4,5];
int *p=&arr[3]; //此时p就是迭代器
p-=2; //p向左移两个单位
begin(); //获取一个容器第一个元素的地址
end(); //获取一个容器最后一个元素的下一个地址(尾后迭代器)
range for循环:
for(int x:arr){ //x表示迭代器的解引用
cout<<x<<endl;
}
auto p=begin(arr); //auto关键字,自动推断指针类型
----------------------------------------------------------------------------------------------------------------------------------------
/**************************************************************************
用迭代器实现冒泡排序
**************************************************************************/
#include <iostream>
using namespace std;
void mysort(int *begin, int *end) {
int *i = end - 1;
int temp;
for (int *it = begin; it != end - 1; it++, i--) {
for (int *j = begin; j != i; j++) {
if (*j > *(j + 1)) {
temp = *j;
*j = *(j + 1);
*(j + 1) = temp;
}
}
}
}
int main() {
int arr[]{ 5,9,3,4,1,6,8,7,2 };
mysort(begin(arr), end(arr));
for (int x : arr) {
cout << x << endl;
}
system("pause");
}
浙公网安备 33010602011771号