Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ new if statement with initializer

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?

like image 588
user3613174 Avatar asked Jan 04 '19 10:01

user3613174


1 Answers

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";
    }
}
like image 119
Yksisarvinen Avatar answered Sep 21 '22 12:09

Yksisarvinen