map operator [] operands

Jamie Cook picture Jamie Cook · May 5, 2010 · Viewed 7.8k times · Source

Hi all I have the following in a member function

int tt = 6; 
vector<set<int>>& temp = m_egressCandidatesByDestAndOtMode[tt]; 
set<int>& egressCandidateStops = temp.at(dest);

and the following declaration of a member variable

map<int, vector<set<int>>> m_egressCandidatesByDestAndOtMode;

However I get an error when compiling (Intel Compiler 11.0)

1>C:\projects\svn\bdk\Source\ZenithAssignment\src\Iteration\PtBranchAndBoundIterationOriginRunner.cpp(85): error: no operator "[]" matches these operands
1>            operand types are: const std::map<int, std::vector<std::set<int, std::less<int>, std::allocator<int>>, std::allocator<std::set<int, std::less<int>, std::allocator<int>>>>, std::less<int>, std::allocator<std::pair<const int, std::vector<std::set<int, std::less<int>, std::allocator<int>>, std::allocator<std::set<int, std::less<int>, std::allocator<int>>>>>>> [ const int ]
1>          vector<set<int>>& temp = m_egressCandidatesByDestAndOtMode[tt]; 
1>                                                                    ^

I know it's got to be something silly but I can't see what I've done wrong.

UPDATE I'm calling this from a const member function which is why the member variable's type is const so I thought that something like the following should fix it:

int dest = 0, tt = 6; 
const set<int>& egressCandidateStops = m_egressCandidatesByDestAndOtMode[tt].at(dest); 

But no dice... still the same error.

Answer

Potatoswatter picture Potatoswatter · May 5, 2010

operand types are: const std::map< int …

map::operator[] does not work with a const map.

I answered this a few days ago.

map::operator[] is a little odd. It does this:

  1. Look for the key.
  2. If found, return it.
  3. If not, insert it and default-construct its associated value.
  4. Then return a reference to the new value.

Step 3 is incompatible with constness. Rather than have two differently-functioning operator[] overloads, the language forces you to use map::find for const objects.