迭代器

image.png
image.png
image.png

  1. #include <vector>
  2. #include <iostream>
  3. using namespace std;
  4. void main() {
  5. vector<int> v;
  6. v.push_back(1); v.push_back(2); v.push_back(3); v.push_back(4);
  7. vector<int>::const_iterator i; // 常量迭代器
  8. for(i = v.begin(); i != v.end(); ++i)
  9. cout << *i << ",";
  10. cout << endl;
  11. vector<int>::reverse_iterator r; // 反向迭代器
  12. for(r = v.rbegin(); r != vrend(); ++r) // ++r 实际上是往前走
  13. cout << *r << ",";
  14. cout << endl;
  15. vector<int>::iterator j; // 非常量迭代器
  16. for(j = v.begin(); j != v.end(); ++j)
  17. *j = 100;
  18. for(i = v.begin(); i != v.end(); ++i)
  19. cout << *i << ",";
  20. cout << endl;
  21. /* 输出:
  22. 1,2,3,4,
  23. 4,3,2,1,
  24. 100,100,100,100,
  25. */
  26. }

双向迭代器

image.png

随机访问迭代器

image.png

不同容器对应迭代器种类

image.png

vector的迭代器是随机访问迭代器

image.png

算法简介

image.png

find()模板

image.png

  1. #include <vector>
  2. #include <algorithm>
  3. #include <iostream>
  4. using namespace std;
  5. void main() {
  6. int array[10] = {10, 20, 30, 40};
  7. vector<int> v;
  8. v.push_back(1); v.push_back(2);
  9. v.push_back(3); v.push_back(4);
  10. vecotr<int>::iterator p;
  11. p = find(v.begin(), v.end(), 3);
  12. if(p != v.end())
  13. cout << *p << endl; // 输出3
  14. p = find(v.begin(), v.end(), 9);
  15. if(p == v.end())
  16. cout << "not found" << endl; // 输出 not found
  17. p = find(v.begin()+1, v.end()-2, 1); //整个容器: [1,2,3,4], 查找区间: [2,3)
  18. if(p != v.end())
  19. cout << *p << endl; // 输出3
  20. int *pp = find(array, array+4, 20);
  21. cout << *pp << endl; // 输出20
  22. }

STL中“大”“小”概念

image.png
image.png

STL中“相等”概念演示

  1. #include <iostream>
  2. #include <algorithm>
  3. using namespace std;
  4. class A {
  5. int v;
  6. public:
  7. A(int n):v(n){}
  8. bool operator < (const A & a) {
  9. cout << v << "<" << a.v << "?" << endl;
  10. return false;
  11. }
  12. bool operator == (const A & a) {
  13. cout << v << "==" << a.v << "?" << endl;
  14. return v == a.v;
  15. }
  16. };
  17. void main() {
  18. A a[] = {A(1), A(2), A(3), A(4), A(5)};
  19. cout << binary_search(a, a+4, A(9));
  20. }
  21. /* 输出:
  22. 3<9?
  23. 2<9?
  24. 1<9?
  25. 9<1?
  26. */