Scho wieder map



  • Hallo,

    hoffe es ist nicht wieder ein repost.
    Gibt es einen tieferen Sinn, dass es keine const Version des []operators in der map gibt bzw. spricht etwas dagegen ihn zu überladen und eine exception zu schmeißen???
    z.B.

    template<typename _Kty, typename _ty, typename _Pr = less<_Kty>, typename _Alloc = allocator<pair<const _Kty, _ty> > >
    class SafeConstMap : public map<_Kty, _ty, _Pr, _Alloc>
    {
    public:
       using map<_Kty, _ty, _Pr, _Alloc>::operator [];
       const _ty& operator[](const _Kty& key) const
       {
          if (find(key) == end())
          {
             cout << "not found" << endl; //Exception sonst rueckgabe undefiniert
          }
          else
          {
             return find(key)->second;
          }
       }
    };
    

  • Mod

    da kann man nur vermutungen anstellen. ich denke das hat etwas mit konsistenz im vergleich zu anderen containern zu tun:
    - kein anderer op[] wirft exceptions.
    - man müsste für diesen zweck eine neue exceptionklasse einführen, das war zu einer zeit, als man die den stl-teil der standard-lib möglichst klein halten wollte von gewisser bedeutung.
    letzlich wird er nicht wirklich gebraucht, im gegensatz zur non-const variante macht er den code, der ihn benutzen würde auch nicht einfacher. überhaupt ist es eher unschön, wenn eine operation, die eigentlich sehr gutmütig ist und nicht wirft (abgesehen von den üblichen kandidaten wie bad_alloc, die sowieso nicht lokal behandelt werden), das plötzlich tut, nur weil ein argument const wird.



  • **http://www.codecomments.com/archive292-2004-12-331681.html**If the key isn't already present in the map, map::operator[] will create a
    new (K,V) pair and store it in the map, returning the V part by reference.
    (Use of this operator requires the mapped_type be default-constructible.)

    You can avoid this behavior by using map::find, though your function as
    specified above will either have to return a default value or throw an
    exception if that function returns end().



  • Warum rufste 2 mal find auf?


Anmelden zum Antworten