STL and templates

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • creativeinspiration
    New Member
    • Jun 2007
    • 25

    STL and templates

    Hey Everybody,
    Question, suppose that I want to write a function that prints out an STL vector of anything that implements a << operator. I am trying to do it like this:

    template <class C>

    void print(vector<C> & v)
    {
    for(int i = 0; i < v.size(); ++i)
    {
    cout << v[i] << " ";
    }
    }

    What is wrong with this? How could I revise this to make it work?
  • Benny the Guard
    New Member
    • Jun 2007
    • 92

    #2
    This should work as long as you have an operator<< defined for class C such as

    Code:
    ostream& operator<< (const C & obj);
    Although you probably want to do a i++ in your for loop otherwise its going to print out the wrong values (always be 1 ahead of where you want to be). You could also use iterators to process this such as:

    Code:
    void print(vector<C>& v)
      {
      vector<C>::interator itr;
      for (itr = v.begin (); itr != v.end (); itr++)
           cout << (*itr);
      }
    One final solution is if you create a function to print a single value then you can use foreach, which calls a function for each object in a container. I like foreach but its a drag to create a function for it.

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      You can also use the copy algorithm.
      [code=cpp]
      copy(v.begin(), v.end(), cout);
      [/code]

      It does the loop for you.

      Comment

      Working...