11

The cppreference page for "if" statement;

https://en.cppreference.com/w/cpp/language/if

gives the following example;

Except that names declared by the init-statement (if init-statement is a declaration) and names declared by condition (if condition is a declaration) are in the same scope, which is also the scope of both statements Blockquote

std::map<int, std::string> m;
if (auto it = m.find(10); it != m.end()) { return it->size(); }

Thats a typo, isn't it? I'm not missing anything here am I, it should be;

it->second.size(); 

or

it->first;

No?

TrebledJ
  • 8,713
  • 7
  • 26
  • 48
user3613174
  • 669
  • 1
  • 7
  • 13

2 Answers2

9

Yes, this is a typo. iterator for std::map will be dereferenced as std::map::value_type, where value_type is std::pair<const Key, T>.

See example of usage for std::map::find (from cppreference):

#include <iostream>
#include <map>
int main()
{  
    std::map<int,char> example = {{1,'a'},{2,'b'}};

    auto search = example.find(2);
    if (search != example.end()) {
        std::cout << "Found " << search->first << " " << search->second << '\n';
    } else {
        std::cout << "Not found\n";
    }
}
Yksisarvinen
  • 18,008
  • 2
  • 24
  • 52
6

You are correct. The code as it is given does not compile. See here. The compiler error is:

error: 'struct std::pair<const int, std::__cxx11::basic_string<char> >' has no member named 'size'

std::pair does not have a size member. But std::string has it.

So the correct code should be:

if (auto it = m.find(10); it != m.end()) { return it->second.size(); }
P.W
  • 26,289
  • 6
  • 39
  • 76