2

I don't understand why this doesn't compile.

#include <string>
#include <set>

struct Foo
{
    struct Rec
    {
        std::string     _s;

        Rec(const std::string& s) : _s(s) {}
        bool operator==(const Rec& r) const { return _s == r._s; }
        bool operator<(const Rec& r) const { return _s < r._s; }
    };

    typedef std::set<Rec>  Recs;

    Recs        _recs;

    Rec* find(const std::string& s)
    {
        Recs::iterator it = _recs.lower_bound(Rec(s));
        if (it != _recs.end())
        {
            // why is `it` const_iterator??
            Rec& r = *it;  // this line doens't compile
            return &r;
        }
        return 0;
    }
};

int main()
{
    return 0;
}

visual c++ error:

foo.cpp(25): error C2440: 'initializing': cannot convert from 'const Foo::Rec' to 'Foo::Rec &'
foo.cpp(25): note: Conversion loses qualifiers

g++ error:

foo.cpp: In member function 'Foo::Rec* Foo::find(const string&)':
foo.cpp:25:23: error: binding 'const Foo::Rec' to reference of type 'Foo::Rec&'
discards qualifiers
             Rec& r = *it;

I want to return a non-const Rec* and i'm not making anything const AFAIK.

thanks,

It looks like my question contains a lot of code....

jkj yuio
  • 2,543
  • 5
  • 32
  • 49

0 Answers0