fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <string>
  4.  
  5. template <class T>
  6. class iterator {
  7. public:
  8. iterator() {}
  9. iterator(std::vector<T> vec) {
  10. container = vec;
  11. }
  12. bool hasNext() {
  13. if (curr_pos == container.size()) {
  14. return false;
  15. } else {
  16. if (curr_pos < container.size()) {
  17. return true;
  18. }
  19. }
  20. return false;
  21. }
  22. T& next(){
  23. if (hasNext()) {
  24. curr_pos += 1;
  25. return container.at(curr_pos-1);
  26. }
  27. }
  28. private:
  29. std::vector<T> container;
  30. int curr_pos = 0;
  31. };
  32.  
  33. int main() {
  34. std::vector<int> int_vec {1,2,3,4};
  35. iterator<int> int_it(int_vec);
  36. while (int_it.hasNext()) {
  37. std::cout << int_it.next() << " ";
  38. }
  39.  
  40. std::cout << std::endl;
  41.  
  42. std::vector<std::string> str_vec {"a", "b", "c","d"};
  43. iterator<std::string> str_it(str_vec);
  44. while(str_it.hasNext()) {
  45. std::cout << str_it.next() << " ";
  46. }
  47. std::cout << std::endl;
  48. std::vector<int> empty_vec;
  49. iterator<int> empty_it(empty_vec);
  50. while(empty_it.hasNext()) {
  51. std::cout << empty_it.next() << " ";
  52. }
  53. return 0;
  54. }
Success #stdin #stdout 0s 3464KB
stdin
Standard input is empty
stdout
1 2 3 4 
a b c d