Ist <list>.begin() nicht konstant?



  • Hallo zusammen,
    beim kompilieren des folgenden Codes bekomme ich diese Meldung:

    g++ -o test test.cpp
    test.cpp: In member function ‘int Test::getAddVal() const’:
    test.cpp:12: error: passing ‘const std::map<int, std::list<int, std::allocator<int> >, std::less<int>, 
    std::allocator<std::pair<const int, std::list<int, std::allocator<int> > > > >’ as ‘this’ argument of 
    ‘_Tp& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const _Key&) [with _Key = int, _Tp = std::list<int, std::allocator<int> >, _Compare = 
    std::less<int>, _Alloc = std::allocator<std::pair<const int, std::list<int, std::allocator<int> > > >]’ discards qualifiers
    

    Wenn ich getAddVal() ohne const schreibe dann funktionierst. Weiss jemand wieso das so ist? Weil eigentlich verändert <list>.begin() ja nichts.

    #include <iostream>
    #include <list>
    #include <map>
    
    class Test {
    public:
    	Test() { 
    		ml[0].push_back(3);
    		ml[0].push_back(5);	
    	};
    	int getAddVal() const {
    		std::list<int>::const_iterator it = ml[0].begin();
    	};
    private:
    	std::map<int, std::list<int> > ml;
    
    };
    
    int main(){
    	Test *test = new Test(); 	
    
    	delete test;
    	return 0;
    }
    

    Gruß



  • Der operator[] der map ist nicht const. find sollte aber gehen: std::list<int>::const_iterator it = ml.find(0)->second.begin();



  • Danke! Es funktioniert jetzt!

    Gruß


Anmelden zum Antworten