Recently came upon this question asked in interview with major tech company.
Implement Java's next and hasNext function in your favorite programming language.
Here is the solution I came up with. I am not sure whether next()
is implemented correctly. Here is the iterator
documentation.
#include <iostream>
#include <vector>
#include <string>
template <class T>
class iterator {
public:
iterator() {}
iterator(std::vector<T> vec) {
container = vec;
}
bool hasNext() {
if (curr_pos == container.size()) {
return false;
} else {
if (curr_pos < container.size()) {
return true;
}
}
return false;
}
T next(){
if (hasNext()) {
curr_pos += 1;
return container.at(curr_pos-1);
}
}
private:
std::vector<T> container;
int curr_pos = 0;
};
int main() {
std::vector<int> int_vec {1,2,3,4};
iterator<int> int_it(int_vec);
while (int_it.hasNext()) {
std::cout << int_it.next() << " ";
}
std::cout << std::endl;
std::vector<std::string> str_vec {"a", "b", "c","d"};
iterator<std::string> str_it(str_vec);
while(str_it.hasNext()) {
std::cout << str_it.next() << " ";
}
std::cout << std::endl;
std::vector<int> empty_vec;
iterator<int> empty_it(empty_vec);
while(empty_it.hasNext()) {
std::cout << empty_it.next() << " ";
}
return 0;
}
Here is the working version of the above code.