C++ const map element access












71















I tried to use the operator access the element in a const C++ map, but this method failed. I also tried to use "at()" to do the same thing. It worked this time. However, I could not find any reference about using "at()" to access element in a const C++ map. Is "at()" a newly added function in C++ map? Where can I find more info about this? Thank you very much!



An example could be the following:



#include <iostream>
#include <map>

using namespace std;

int main()
{
map<int, char> A;
A[1] = 'b';
A[3] = 'c';

const map<int, char> B = A;

cout << B.at(3) << endl; // it works
cout << B[3] << endl; // it does not work

}


For using "B[3]", it returned the following errors during compiling:




t01.cpp:14: error: passing ‘const
std::map,
std::allocator > >’ as ‘this’ argument of ‘_Tp&
std::map<_Key, _Tp, _Compare,
_Alloc>::operator(const _Key&) [with _Key = int, _Tp = char, _Compare = std::less, _Alloc =
std::allocator >]’ discards qualifiers




The compiler used is g++ 4.2.1










share|improve this question



























    71















    I tried to use the operator access the element in a const C++ map, but this method failed. I also tried to use "at()" to do the same thing. It worked this time. However, I could not find any reference about using "at()" to access element in a const C++ map. Is "at()" a newly added function in C++ map? Where can I find more info about this? Thank you very much!



    An example could be the following:



    #include <iostream>
    #include <map>

    using namespace std;

    int main()
    {
    map<int, char> A;
    A[1] = 'b';
    A[3] = 'c';

    const map<int, char> B = A;

    cout << B.at(3) << endl; // it works
    cout << B[3] << endl; // it does not work

    }


    For using "B[3]", it returned the following errors during compiling:




    t01.cpp:14: error: passing ‘const
    std::map,
    std::allocator > >’ as ‘this’ argument of ‘_Tp&
    std::map<_Key, _Tp, _Compare,
    _Alloc>::operator(const _Key&) [with _Key = int, _Tp = char, _Compare = std::less, _Alloc =
    std::allocator >]’ discards qualifiers




    The compiler used is g++ 4.2.1










    share|improve this question

























      71












      71








      71


      13






      I tried to use the operator access the element in a const C++ map, but this method failed. I also tried to use "at()" to do the same thing. It worked this time. However, I could not find any reference about using "at()" to access element in a const C++ map. Is "at()" a newly added function in C++ map? Where can I find more info about this? Thank you very much!



      An example could be the following:



      #include <iostream>
      #include <map>

      using namespace std;

      int main()
      {
      map<int, char> A;
      A[1] = 'b';
      A[3] = 'c';

      const map<int, char> B = A;

      cout << B.at(3) << endl; // it works
      cout << B[3] << endl; // it does not work

      }


      For using "B[3]", it returned the following errors during compiling:




      t01.cpp:14: error: passing ‘const
      std::map,
      std::allocator > >’ as ‘this’ argument of ‘_Tp&
      std::map<_Key, _Tp, _Compare,
      _Alloc>::operator(const _Key&) [with _Key = int, _Tp = char, _Compare = std::less, _Alloc =
      std::allocator >]’ discards qualifiers




      The compiler used is g++ 4.2.1










      share|improve this question














      I tried to use the operator access the element in a const C++ map, but this method failed. I also tried to use "at()" to do the same thing. It worked this time. However, I could not find any reference about using "at()" to access element in a const C++ map. Is "at()" a newly added function in C++ map? Where can I find more info about this? Thank you very much!



      An example could be the following:



      #include <iostream>
      #include <map>

      using namespace std;

      int main()
      {
      map<int, char> A;
      A[1] = 'b';
      A[3] = 'c';

      const map<int, char> B = A;

      cout << B.at(3) << endl; // it works
      cout << B[3] << endl; // it does not work

      }


      For using "B[3]", it returned the following errors during compiling:




      t01.cpp:14: error: passing ‘const
      std::map,
      std::allocator > >’ as ‘this’ argument of ‘_Tp&
      std::map<_Key, _Tp, _Compare,
      _Alloc>::operator(const _Key&) [with _Key = int, _Tp = char, _Compare = std::less, _Alloc =
      std::allocator >]’ discards qualifiers




      The compiler used is g++ 4.2.1







      c++ stl map const






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Feb 27 '11 at 17:17









      icephereicephere

      465145




      465145
























          4 Answers
          4






          active

          oldest

          votes


















          96














          at() is a new method for std::map in C++11.



          Rather than insert a new default constructed element as operator does if an element with the given key does not exist, it throws a std::out_of_range exception. (This is similar to the behaviour of at() for deque and vector.)



          Because of this behaviour it makes sense for there to be a const overload of at(), unlike operator which always has the potential to change the map.






          share|improve this answer


























          • Is is possible to have "at" return a default value instead of throwing an exception?

            – user1202136
            Aug 30 '12 at 14:41











          • at() should be C++11 only

            – Deqing
            Aug 9 '13 at 10:54











          • I'm using at() with in VS2013 on a project set to use VS2010 toolkit. I thought that meant I wasn't using C++11... But yet it compiles... ??

            – thomthom
            Dec 7 '13 at 22:27






          • 1





            I just need to comment that it doesn't make sense to omit the const operator, which could also throw an exception for an unmapped element instead of changing the map.

            – Spencer
            Mar 1 '18 at 15:37











          • @Spencer It would be surprising if the const and non-const overloads of operator had different effects. Normally, we expect that if some non-const objects or references in a program are made const, the program will continue to behave in the same way, as long as it compiles. Allowing only the non-const overload to throw exceptions can result in bugs that are not caught until runtime.

            – Brian
            Feb 25 at 17:55



















          29














          If an element doesn’t exist in a map, the operator will add it – which obviously cannot work in a const map so C++ does not define a const version of the operator. This is a nice example of the compiler’s type checker preventing a potential runtime error.



          In your case, you need to use find instead which will only return an (iterator to the) element if it exists, it will never modify the map. If an item doesn’t exist, it returns an iterator to the map’s end().



          at doesn’t exist and shouldn’t even compile. Perhaps this is a “compiler extension” (= a bug new in C++0x).






          share|improve this answer


























          • Does the C++ standard forbid the implementation from defining additional non-standard member functions in library classes?

            – Tim Martin
            Feb 27 '11 at 17:31











          • @Tim I believe the interface is fixed, yes.

            – Konrad Rudolph
            Feb 27 '11 at 17:33



















          3














          The -operator will create a new entry in the map if the given key does not exists. It may thus change the map.



          See this link.






          share|improve this answer































            2














            This comes as quite a surprise to me, but the STL map doesn't have a const index operator. That is, B[3] cannot be read-only. From the manual:



            Since operator might insert a new element into the map, it can't possibly be a const member function.



            I have no idea about at().






            share|improve this answer























              Your Answer






              StackExchange.ifUsing("editor", function () {
              StackExchange.using("externalEditor", function () {
              StackExchange.using("snippets", function () {
              StackExchange.snippets.init();
              });
              });
              }, "code-snippets");

              StackExchange.ready(function() {
              var channelOptions = {
              tags: "".split(" "),
              id: "1"
              };
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function() {
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled) {
              StackExchange.using("snippets", function() {
              createEditor();
              });
              }
              else {
              createEditor();
              }
              });

              function createEditor() {
              StackExchange.prepareEditor({
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader: {
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              },
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              });


              }
              });














              draft saved

              draft discarded


















              StackExchange.ready(
              function () {
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f5134614%2fc-const-map-element-access%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              4 Answers
              4






              active

              oldest

              votes








              4 Answers
              4






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              96














              at() is a new method for std::map in C++11.



              Rather than insert a new default constructed element as operator does if an element with the given key does not exist, it throws a std::out_of_range exception. (This is similar to the behaviour of at() for deque and vector.)



              Because of this behaviour it makes sense for there to be a const overload of at(), unlike operator which always has the potential to change the map.






              share|improve this answer


























              • Is is possible to have "at" return a default value instead of throwing an exception?

                – user1202136
                Aug 30 '12 at 14:41











              • at() should be C++11 only

                – Deqing
                Aug 9 '13 at 10:54











              • I'm using at() with in VS2013 on a project set to use VS2010 toolkit. I thought that meant I wasn't using C++11... But yet it compiles... ??

                – thomthom
                Dec 7 '13 at 22:27






              • 1





                I just need to comment that it doesn't make sense to omit the const operator, which could also throw an exception for an unmapped element instead of changing the map.

                – Spencer
                Mar 1 '18 at 15:37











              • @Spencer It would be surprising if the const and non-const overloads of operator had different effects. Normally, we expect that if some non-const objects or references in a program are made const, the program will continue to behave in the same way, as long as it compiles. Allowing only the non-const overload to throw exceptions can result in bugs that are not caught until runtime.

                – Brian
                Feb 25 at 17:55
















              96














              at() is a new method for std::map in C++11.



              Rather than insert a new default constructed element as operator does if an element with the given key does not exist, it throws a std::out_of_range exception. (This is similar to the behaviour of at() for deque and vector.)



              Because of this behaviour it makes sense for there to be a const overload of at(), unlike operator which always has the potential to change the map.






              share|improve this answer


























              • Is is possible to have "at" return a default value instead of throwing an exception?

                – user1202136
                Aug 30 '12 at 14:41











              • at() should be C++11 only

                – Deqing
                Aug 9 '13 at 10:54











              • I'm using at() with in VS2013 on a project set to use VS2010 toolkit. I thought that meant I wasn't using C++11... But yet it compiles... ??

                – thomthom
                Dec 7 '13 at 22:27






              • 1





                I just need to comment that it doesn't make sense to omit the const operator, which could also throw an exception for an unmapped element instead of changing the map.

                – Spencer
                Mar 1 '18 at 15:37











              • @Spencer It would be surprising if the const and non-const overloads of operator had different effects. Normally, we expect that if some non-const objects or references in a program are made const, the program will continue to behave in the same way, as long as it compiles. Allowing only the non-const overload to throw exceptions can result in bugs that are not caught until runtime.

                – Brian
                Feb 25 at 17:55














              96












              96








              96







              at() is a new method for std::map in C++11.



              Rather than insert a new default constructed element as operator does if an element with the given key does not exist, it throws a std::out_of_range exception. (This is similar to the behaviour of at() for deque and vector.)



              Because of this behaviour it makes sense for there to be a const overload of at(), unlike operator which always has the potential to change the map.






              share|improve this answer















              at() is a new method for std::map in C++11.



              Rather than insert a new default constructed element as operator does if an element with the given key does not exist, it throws a std::out_of_range exception. (This is similar to the behaviour of at() for deque and vector.)



              Because of this behaviour it makes sense for there to be a const overload of at(), unlike operator which always has the potential to change the map.







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Aug 28 '13 at 14:38







              user283145

















              answered Feb 27 '11 at 17:29









              CB BaileyCB Bailey

              521k78559614




              521k78559614













              • Is is possible to have "at" return a default value instead of throwing an exception?

                – user1202136
                Aug 30 '12 at 14:41











              • at() should be C++11 only

                – Deqing
                Aug 9 '13 at 10:54











              • I'm using at() with in VS2013 on a project set to use VS2010 toolkit. I thought that meant I wasn't using C++11... But yet it compiles... ??

                – thomthom
                Dec 7 '13 at 22:27






              • 1





                I just need to comment that it doesn't make sense to omit the const operator, which could also throw an exception for an unmapped element instead of changing the map.

                – Spencer
                Mar 1 '18 at 15:37











              • @Spencer It would be surprising if the const and non-const overloads of operator had different effects. Normally, we expect that if some non-const objects or references in a program are made const, the program will continue to behave in the same way, as long as it compiles. Allowing only the non-const overload to throw exceptions can result in bugs that are not caught until runtime.

                – Brian
                Feb 25 at 17:55



















              • Is is possible to have "at" return a default value instead of throwing an exception?

                – user1202136
                Aug 30 '12 at 14:41











              • at() should be C++11 only

                – Deqing
                Aug 9 '13 at 10:54











              • I'm using at() with in VS2013 on a project set to use VS2010 toolkit. I thought that meant I wasn't using C++11... But yet it compiles... ??

                – thomthom
                Dec 7 '13 at 22:27






              • 1





                I just need to comment that it doesn't make sense to omit the const operator, which could also throw an exception for an unmapped element instead of changing the map.

                – Spencer
                Mar 1 '18 at 15:37











              • @Spencer It would be surprising if the const and non-const overloads of operator had different effects. Normally, we expect that if some non-const objects or references in a program are made const, the program will continue to behave in the same way, as long as it compiles. Allowing only the non-const overload to throw exceptions can result in bugs that are not caught until runtime.

                – Brian
                Feb 25 at 17:55

















              Is is possible to have "at" return a default value instead of throwing an exception?

              – user1202136
              Aug 30 '12 at 14:41





              Is is possible to have "at" return a default value instead of throwing an exception?

              – user1202136
              Aug 30 '12 at 14:41













              at() should be C++11 only

              – Deqing
              Aug 9 '13 at 10:54





              at() should be C++11 only

              – Deqing
              Aug 9 '13 at 10:54













              I'm using at() with in VS2013 on a project set to use VS2010 toolkit. I thought that meant I wasn't using C++11... But yet it compiles... ??

              – thomthom
              Dec 7 '13 at 22:27





              I'm using at() with in VS2013 on a project set to use VS2010 toolkit. I thought that meant I wasn't using C++11... But yet it compiles... ??

              – thomthom
              Dec 7 '13 at 22:27




              1




              1





              I just need to comment that it doesn't make sense to omit the const operator, which could also throw an exception for an unmapped element instead of changing the map.

              – Spencer
              Mar 1 '18 at 15:37





              I just need to comment that it doesn't make sense to omit the const operator, which could also throw an exception for an unmapped element instead of changing the map.

              – Spencer
              Mar 1 '18 at 15:37













              @Spencer It would be surprising if the const and non-const overloads of operator had different effects. Normally, we expect that if some non-const objects or references in a program are made const, the program will continue to behave in the same way, as long as it compiles. Allowing only the non-const overload to throw exceptions can result in bugs that are not caught until runtime.

              – Brian
              Feb 25 at 17:55





              @Spencer It would be surprising if the const and non-const overloads of operator had different effects. Normally, we expect that if some non-const objects or references in a program are made const, the program will continue to behave in the same way, as long as it compiles. Allowing only the non-const overload to throw exceptions can result in bugs that are not caught until runtime.

              – Brian
              Feb 25 at 17:55













              29














              If an element doesn’t exist in a map, the operator will add it – which obviously cannot work in a const map so C++ does not define a const version of the operator. This is a nice example of the compiler’s type checker preventing a potential runtime error.



              In your case, you need to use find instead which will only return an (iterator to the) element if it exists, it will never modify the map. If an item doesn’t exist, it returns an iterator to the map’s end().



              at doesn’t exist and shouldn’t even compile. Perhaps this is a “compiler extension” (= a bug new in C++0x).






              share|improve this answer


























              • Does the C++ standard forbid the implementation from defining additional non-standard member functions in library classes?

                – Tim Martin
                Feb 27 '11 at 17:31











              • @Tim I believe the interface is fixed, yes.

                – Konrad Rudolph
                Feb 27 '11 at 17:33
















              29














              If an element doesn’t exist in a map, the operator will add it – which obviously cannot work in a const map so C++ does not define a const version of the operator. This is a nice example of the compiler’s type checker preventing a potential runtime error.



              In your case, you need to use find instead which will only return an (iterator to the) element if it exists, it will never modify the map. If an item doesn’t exist, it returns an iterator to the map’s end().



              at doesn’t exist and shouldn’t even compile. Perhaps this is a “compiler extension” (= a bug new in C++0x).






              share|improve this answer


























              • Does the C++ standard forbid the implementation from defining additional non-standard member functions in library classes?

                – Tim Martin
                Feb 27 '11 at 17:31











              • @Tim I believe the interface is fixed, yes.

                – Konrad Rudolph
                Feb 27 '11 at 17:33














              29












              29








              29







              If an element doesn’t exist in a map, the operator will add it – which obviously cannot work in a const map so C++ does not define a const version of the operator. This is a nice example of the compiler’s type checker preventing a potential runtime error.



              In your case, you need to use find instead which will only return an (iterator to the) element if it exists, it will never modify the map. If an item doesn’t exist, it returns an iterator to the map’s end().



              at doesn’t exist and shouldn’t even compile. Perhaps this is a “compiler extension” (= a bug new in C++0x).






              share|improve this answer















              If an element doesn’t exist in a map, the operator will add it – which obviously cannot work in a const map so C++ does not define a const version of the operator. This is a nice example of the compiler’s type checker preventing a potential runtime error.



              In your case, you need to use find instead which will only return an (iterator to the) element if it exists, it will never modify the map. If an item doesn’t exist, it returns an iterator to the map’s end().



              at doesn’t exist and shouldn’t even compile. Perhaps this is a “compiler extension” (= a bug new in C++0x).







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Feb 27 '11 at 17:34

























              answered Feb 27 '11 at 17:24









              Konrad RudolphKonrad Rudolph

              401k1017901038




              401k1017901038













              • Does the C++ standard forbid the implementation from defining additional non-standard member functions in library classes?

                – Tim Martin
                Feb 27 '11 at 17:31











              • @Tim I believe the interface is fixed, yes.

                – Konrad Rudolph
                Feb 27 '11 at 17:33



















              • Does the C++ standard forbid the implementation from defining additional non-standard member functions in library classes?

                – Tim Martin
                Feb 27 '11 at 17:31











              • @Tim I believe the interface is fixed, yes.

                – Konrad Rudolph
                Feb 27 '11 at 17:33

















              Does the C++ standard forbid the implementation from defining additional non-standard member functions in library classes?

              – Tim Martin
              Feb 27 '11 at 17:31





              Does the C++ standard forbid the implementation from defining additional non-standard member functions in library classes?

              – Tim Martin
              Feb 27 '11 at 17:31













              @Tim I believe the interface is fixed, yes.

              – Konrad Rudolph
              Feb 27 '11 at 17:33





              @Tim I believe the interface is fixed, yes.

              – Konrad Rudolph
              Feb 27 '11 at 17:33











              3














              The -operator will create a new entry in the map if the given key does not exists. It may thus change the map.



              See this link.






              share|improve this answer




























                3














                The -operator will create a new entry in the map if the given key does not exists. It may thus change the map.



                See this link.






                share|improve this answer


























                  3












                  3








                  3







                  The -operator will create a new entry in the map if the given key does not exists. It may thus change the map.



                  See this link.






                  share|improve this answer













                  The -operator will create a new entry in the map if the given key does not exists. It may thus change the map.



                  See this link.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Feb 27 '11 at 17:28









                  vidstigevidstige

                  8,49054487




                  8,49054487























                      2














                      This comes as quite a surprise to me, but the STL map doesn't have a const index operator. That is, B[3] cannot be read-only. From the manual:



                      Since operator might insert a new element into the map, it can't possibly be a const member function.



                      I have no idea about at().






                      share|improve this answer




























                        2














                        This comes as quite a surprise to me, but the STL map doesn't have a const index operator. That is, B[3] cannot be read-only. From the manual:



                        Since operator might insert a new element into the map, it can't possibly be a const member function.



                        I have no idea about at().






                        share|improve this answer


























                          2












                          2








                          2







                          This comes as quite a surprise to me, but the STL map doesn't have a const index operator. That is, B[3] cannot be read-only. From the manual:



                          Since operator might insert a new element into the map, it can't possibly be a const member function.



                          I have no idea about at().






                          share|improve this answer













                          This comes as quite a surprise to me, but the STL map doesn't have a const index operator. That is, B[3] cannot be read-only. From the manual:



                          Since operator might insert a new element into the map, it can't possibly be a const member function.



                          I have no idea about at().







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Feb 27 '11 at 17:27









                          BetaBeta

                          72.5k7110129




                          72.5k7110129






























                              draft saved

                              draft discarded




















































                              Thanks for contributing an answer to Stack Overflow!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid



                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.


                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function () {
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f5134614%2fc-const-map-element-access%23new-answer', 'question_page');
                              }
                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              這個網誌中的熱門文章

                              Tangent Lines Diagram Along Smooth Curve

                              Yusuf al-Mu'taman ibn Hud

                              Zucchini