Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

map operator [] operands

Tags:

c++

map

operands

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.

like image 309
Jamie Cook Avatar asked May 05 '10 10:05

Jamie Cook


2 Answers

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.

like image 196
Potatoswatter Avatar answered Oct 22 '22 05:10

Potatoswatter


The prototype for [] is

 data_type& operator[](const key_type& k)

i.e. a non const operation, so you can't call it on a member from a const member function .

You could change the code to:

std::map<...>::const_iterator where = m_egressCandidatesByDestAndOtMode.find(tt);
if (egressCandidatesByDestAndOtMode.end() != where) {
    const vector<set<int>>& temp = where->second;
}
like image 41
Andreas Brinck Avatar answered Oct 22 '22 04:10

Andreas Brinck