Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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];
// }
like image 479
M.A Avatar asked Nov 16 '12 09:11

M.A


People also ask

How do you access vectors using iterators?

Use a for loop and reference pointer In C++ , vectors can be indexed with []operator , similar to arrays. To iterate through the vector, run a for loop from i = 0 to i = vec.

What are iterators iterators are used to?

Iterators play a critical role in connecting algorithm with containers along with the manipulation of data stored inside the containers. The most obvious form of iterator is a pointer. A pointer can point to elements in an array, and can iterate through them using the increment operator (++).


2 Answers

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());
like image 85
juanchopanza Avatar answered Sep 22 '22 12:09

juanchopanza


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;
}
like image 36
Denis Ermolin Avatar answered Sep 22 '22 12:09

Denis Ermolin