Thread: const error

  1. #1
    Registered User
    Join Date
    Oct 2005
    Posts
    271

    const error

    I'm working with a standard container and it keeps getting a compile error about discarded const qualifiers even though I'm not making any changes to it.

    Code:
    void foo(const map<string, pair<int, int> >& m)
    {
       string search_string = "bar";
       int a = m[search_string].first;            // !Error about "passing const map<yadayada> as
                                                  //'this' argument of "yada yada" discards qualifiers"
       int b = m[seach_string].second; 
    }
    
    // the second yada yada in this case is 
    //'std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const _Key&) [with _Key = 
    //std::basic_string<char, std::char_traits<char>, std::allocator<char> >, _Tp = std::pair<unsigned int, 
    //unsigned int>, _Compare = std::less<std::basic_string<char, std::char_traits<char>, 
    //std::allocator<char> > >, _Alloc = std::allocator<std::pair<const std::basic_string<char, 
    //std::char_traits<char>, std::allocator<char> >, std::pair<unsigned int, unsigned int> > >]’
    Do I have to use the dreaded const_cast?

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    According to my searches, map:: operator [] is not a const function (in other words, if search_string is not a key value, a new key will be created, hence m will be modified). If you need to work with const, you should use map::find instead.
    Last edited by tabstop; 02-21-2008 at 07:03 PM. Reason: I hate smileys :)

  3. #3
    Registered User
    Join Date
    Oct 2005
    Posts
    271
    Of course. Forgot about that. Thanks!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Quantum Random Bit Generator
    By shawnt in forum C++ Programming
    Replies: 62
    Last Post: 06-18-2008, 10:17 AM
  2. Avoiding Global variables
    By csonx_p in forum Windows Programming
    Replies: 32
    Last Post: 05-19-2008, 12:17 AM
  3. Game Pointer Trouble?
    By Drahcir in forum C Programming
    Replies: 8
    Last Post: 02-04-2006, 02:53 AM
  4. Half-life SDK, where are the constants?
    By bennyandthejets in forum Game Programming
    Replies: 29
    Last Post: 08-25-2003, 11:58 AM
  5. Linking error
    By DockyD in forum C++ Programming
    Replies: 10
    Last Post: 01-20-2003, 05:27 AM