problem with operator<< overloading

May 7, 2016 at 3:46pm
I am getting errors in my code. Can someone help me because i can't fix it?


1
2
3
4
5
6
7
8
9
10
11
12
std::ostream & operator<<(std::ostream &os,const std::list<int> &toBePrinted){
    std::list<int>::iterator lIterator;
    
    std::cout<<"(";
    

    for(lIterator=toBePrinted.begin();lIterator!=toBePrinted.end()-1;lIterator++){
        os<<*lIterator<<", ";
    }
    os<<*toBePrinted.end()<<")"<<std::endl;
    return os;
}

//the for loop line has following 2 errors:
error: no viable overloaded '='
error: invalid operands to binary expression ('const iterator' (aka '_List_const_iterator<int>') and 'int')
Last edited on May 7, 2016 at 3:47pm
May 7, 2016 at 4:13pm
The end()-1 seems to be part of the issue.

What if you print the first item separately and the << ", " << value for the rest items?

PS. Line 10 has undefined behaviour and line 4 has that cout ...
May 7, 2016 at 4:18pm
hmm, yes

but what should i write when the loop is supposed to break at the last but one?

in Line 10 you mean *toBePrinted.end()???
Last edited on May 7, 2016 at 4:21pm
May 7, 2016 at 4:47pm
The .end() for an iterator does not refer to the last legitimate item but the sentinel item in the container.

To accomplish what you want maybe try the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
std::ostream & operator <<(std::ostream &os, const std::list<int> &toBePrinted)
{
    std::list<int>::const_iterator lIterator;
    
    std::cout<<"(";
    

    bool hasPrevious = false;
    for(lIterator=toBePrinted.begin(); lIterator!=toBePrinted.end(); lIterator++)
    {
        if (hasPrevious)       os << ", ";
        hasPrevious = true;

        os << *lIterator;
    }

    os  << ")" <<std::endl;
    return os;
}
May 8, 2016 at 6:27am
Thank you very much, it works well!!!
Topic archived. No new replies allowed.