M.A
M.A

Reputation: 1133

Generic Iterators to access vectors

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];
// }

Upvotes: 5

Views: 678

Answers (2)

juanchopanza
juanchopanza

Reputation: 227508

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());

Upvotes: 5

Denis Ermolin
Denis Ermolin

Reputation: 5556

template<typename VectorObject>
void Display(VecObject v) {
   typename VectorObject::const_iterator it = v.begin();
   for (; it!=v.end(); ++it) {
      cout << *it << endl;
   }
}

Assume that your VectorObject implements iterators you can access to it's iterator type directly.

Usage:

int main()
{
  std::vector<int> intv(2, 5);
  std::vector<float> fv(2, 10);
  Display(intv);
  Display(fv);
  return 0;
}

Upvotes: 3

Related Questions