Generic Iterators to access vectors
c++, iterator, stdvector
Solution
You have access to a `vector`'s iterator types via `iterator` and `const_iterator`, so you need no switching:
template <typename VecObject>
void Display(const VecObject& v) {
typename VecObject::const_iterator it;
for ( it = v.begin(); it!=v.end(); ++it) {
cout << *it << endl;
}
}
Note that I changed the signature to take a const reference as opposed to a value. With the original signature, you would be needlessly copying the vector each time you call the function.
Alternatively, you can implement the function to take two iterators:
template <typename Iterator>
void Display(Iterator first, Iterator last) {
for (Iterator it = first; it!=last; ++it) {
cout << *it << endl;
}
}
and call it like this:
Display(v.begin(), v.end());
Problem
I would like to know if I can have a generic iterator to access the elements in the the vectors. I have for different vectors but only one function to display the elements. If I can have a generic iterator than my method can work out smoothly. Please advice if it is possible. Point2,Point3,Line2,Line3 are 4 different classes. The method takes in a vector object which I have created in another method. ``` template <typename VecObject> void Display(VecObject v) { if (filterCriteria == "Point2") { vector<Point2>::iterator it; } else if (filterCriteria == "Point3") { } else if (filterCriteria == "Line2") { } else if (filterCriteria == "Line3") { } for ( it = v.begin(); it!=v.end(); ++it) { cout << *it << endl; } } ``` This what i used to do ealier and it work find. I now need to to implement using iterators ``` //for (int i = 0; i < v.size(); i++) { // cout << v[i]; // } ```