It is my understanding that std::find_if() below
returns an iterator to the first element in the range of arg
for which the third argument (lamda function) returns true. Is that correct?
Could somebody explain why there isn't an iterator defined like this std::pair<std::string, std::type_index>::iterator = std::find_if(...)
?
Where is the iterator returned by std::find_if()
stored and how can you call ->second
on its own and not on an iterator?
std::type_index argType(const std::string& name) const
{
return std::find_if(args_.begin(), args_.end(),
[&name](std::pair<std::string, std::type_index> arg)->bool
{
return arg.first == name;
}
)->second;
}
It is my understanding that
std::find_if()
below returns an iterator
Yes, but that iterator is then dereferenced within the same expression. The function returns a copy of the std::type_index
from some element of args_
, which is presumably some std-like container with a value_type
of std::pair<std::string, std::type_index>
(or similar).
At a guess it's a std::vector<std::pair<std::string, std::type_index>>
, because if it were a map the whole function could be simplified to
return args_.at(name);
Could somebody explain why there isn't an iterator defined like this
std::pair<std::string, std::type_index>::iterator = std::find_if(...)
?
Well firstly std::pair
doesn't have a member iterator
. I assume you meant std::vector<std::pair<std::string, std::type_index>>::iterator
(or whichever collection type args_
is).
There doesn't need to be a separate statement declaring such an iterator, in much the same way as you don't need a separate double
in the statement
return floor(3.14 * radius);
when you want an integer circumference calculation.
Where is the iterator returned by
std::find_if()
stored
Anywhere the compiler likes. It only exists while the return statement is being evaluated.
how can you call
->second
on its own
You aren't. You are calling it on the temporary returned by std::find_if
and why is there a
!= args_.end()
after the closing brace ofstd::find_if
?
There isn't. The author assumes that they will find a matching element. If they don't, the program has undefined behaviour. That may be intentional, or it may be a bug.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.