Thread: Help about STL copy algorithm

  1. #1
    C/C++Newbie Antigloss's Avatar
    Join Date
    May 2005

    Help about STL copy algorithm

    I defined a class `test' and also overloaded the << operator for it. It came out that I can apply cout to objects of test to print the contents to the console, but I got stuck when trying to print them to the console using copy. It'll be a compile-time error when using copy!

    Is there anything wrong with my code? Do I need to overload more operators?

    #include <algorithm>
    #include <iostream>
    #include <iterator>
    #include <string>
    #include <vector>
    using namespace std;
    class test {
            friend ostream& operator <<(ostream &out, test &t);
            test(int n) { a = n; }
            int a;
    int main()
            vector<test> vec;
            for ( vector<test>::iterator it = vec.begin(); it != vec.end(); ++it )
                    cout << *it << ' ';
    // compile-time error when using copy
    //        copy(vec.begin(), vec.end(), ostream_iterator<test>(cout, " "));
            cout << endl;
    ostream& operator <<(ostream &out, test &t)
            return (out << t.a);

  2. #2
    Ethernal Noob
    Join Date
    Nov 2001
    it works for me. No compile time errors at all.

  3. #3
    C/C++Newbie Antigloss's Avatar
    Join Date
    May 2005
    that's because I commented out the errorous code
    //        copy(vec.begin(), vec.end(), ostream_iterator<test>(cout, " "));
    it'll be a compile-time error if you uncomment this line.

  4. #4
    Registered User Tonto's Avatar
    Join Date
    Jun 2005
    New York
    Works if I make your operator << take const 'test' references

  5. #5
    The larch
    Join Date
    May 2006
    As a general rule, if you are not going to change something, declare it const. The standard libraries apparently require your code to be const-correct.
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. calling copy constructor from template
    By Ancient Dragon in forum C++ Programming
    Replies: 3
    Last Post: 09-28-2005, 01:54 PM
  2. Request for comments
    By Prelude in forum A Brief History of
    Replies: 15
    Last Post: 01-02-2004, 10:33 AM
  3. copy algorithm
    By kes103 in forum C++ Programming
    Replies: 4
    Last Post: 06-19-2003, 08:48 AM
  4. STL algorithm question
    By Reggie in forum C++ Programming
    Replies: 1
    Last Post: 04-22-2003, 09:04 AM