ditmark12
ditmark12

Reputation: 121

Compiler Error on iterator using list<Object*> C++

I have been having some troubles with the following code.

#ifndef SGA_H
#define SGA_H

#include<list>
#include "BaseObject.h"
#include "TableSpace.h"

class SGA : public BaseObject {
private:
    list<TableSpace*> TB;
public:
    SGA();
    SGA(list<TableSpace*>);
    void save(ostream&) const;
    static SGA* read(ifstream&);
    string toString() const;
};

#endif  /* SGA_H */

Problematic code

void SGA::save(ostream& out) const{
    salida << "SGA" << endl;
    salida << TB.size() << endl;
    list<TableSpace*>::iterator it;
    for(it = TB.begin(); it != TB.end();it++){
        it->save(out);
    }
}

And this one too

string SGA::toString() const{
    stringstream cadena;

    cadena << "\nTable Spaces: ";
    list<TableSpace>::iterator i;
    for(i=TB.begin(); i != TB.end(); i++){
        cadena << (*i).toString();
    }
    return cadena.str();
}

What the compiler says is that there is no coincidence in operator =

Exactly the output is:

SGA.cpp:14:23: error: no coincidence 'operator=' en 'it = ((const SGA*)this)->SGA::TB.std::list<_Tp, _Alloc>::begin [with _Tp = TableSpace*, _Alloc = std::allocator<TableSpace*>, std::list<_Tp, _Alloc>::const_iterator = std::_List_const_iterator<TableSpace*>]()'

Upvotes: 0

Views: 88

Answers (4)

Suryavanshi
Suryavanshi

Reputation: 605

As the functions in question are const, you should use const_iterator

For example:

class test{
    public:
    list<int> x;
    test(){
    }
    int get() const{
      list<int>::iterator i;
      for(i=x.begin();i!=x.end();i++)
        return *i;
    }
};

int main() {
    test a=test();
    a.x.push_back(10);
    cout<<a.get();
    return 0;
}

reproduces your error. While using const_iterator error is resolved. http://ideone.com/e.js/zDyuQU

class test{
    public:
    list<int> x;
    test(){
    }
    int get() const{
      list<int>::const_iterator i;
      for(i=x.begin();i!=x.end();i++)
        return *i;
    }
};

int main() {
    test a=test();
    a.x.push_back(10);
    cout<<a.get();
    return 0;
}

Upvotes: 0

ST3
ST3

Reputation: 8946

you should try:

list<TableSpace*>::iterator it;
for(it = TB.begin(); it != TB.end();it++){
    (*it)->save(out);

Because after iteration you get a pointer to pointer.


Also, do you really need to declare all these methods const?? Are sure that it means?

Upvotes: 2

Ferenc Deak
Ferenc Deak

Reputation: 35408

you define the iterator as list<TableSpace>::iterator i; but try to iterate over a list<TableSpace*> TB; ... this might be an error.

Upvotes: 1

Callidior
Callidior

Reputation: 2904

Try using a const_iterator instead of iterator:

list<TableSpace*>::const_iterator it;

Upvotes: 1

Related Questions