chap3_2.cpp 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. #include <iostream>
  2. #include <vector>
  3. //#include <iterator>
  4. using namespace std;
  5. template <typename T>
  6. void display(const vector<T>& vec, ostream& os=cout) {
  7. //const_iterator 敲错了
  8. // 编译错误need 'typename' before *** because *** is a dependent scope; https://blog.csdn.net/pb1995/article/details/49532285/
  9. typename vector<T>::const_iterator it = vec.begin();
  10. typename vector<T>::const_iterator it_end = vec.end();
  11. for (; it != it_end; ++it) {
  12. os << *it << ' ';
  13. }
  14. os << endl;
  15. }
  16. template <typename IteratorType, typename elemType>
  17. IteratorType myfind(IteratorType first, IteratorType last, const elemType& value) {
  18. for (; first != last; ++first) {
  19. if (value == *first)
  20. return first;
  21. }
  22. return last;
  23. }
  24. /*
  25. template <typename elemType>
  26. void display_vector(const vector<elemType>& vec, ostream& os = cout, int len = 8)
  27. {
  28. typename vector<elemType>::const_iterator
  29. iter = vec.begin(),
  30. end_it = vec.end();
  31. int elem_cnt = 1;
  32. while (iter != end_it) {
  33. os << *iter++
  34. << (!(elem_cnt++ % len) ? '\n' : ' '); // 一行8个字符串
  35. os << endl;
  36. }
  37. }
  38. */
  39. int main() {
  40. vector<int> vec = { 12,3,4,5 };
  41. display(vec);
  42. vector<int>::iterator it;
  43. it = myfind(vec.begin(), vec.end(), 3);
  44. cout << *it << endl;
  45. return 0;
  46. }