C++ new if statement with initializer

  • A+
Category:Languages

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?

 


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";     } } 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: