Just wanted to point out that one shouldn't be using
new
, unless one is writing a library. Especially since in this example a STL container is being used. STL containers already put their data on the heap, and it is bad to use new purely to obtain a pointer. The problem with new is if something throws an exception, the (non existent in this case) delete is never reached, so there is a memory leak.
There is a range based for loop, which is good when one wants to iterate all the items in the container, so one doesn't have to use iterators at all, or even worry about pointers at all.Try to do value or reference semantics, not pointer semantics.
The first version is the safest and ideal : it handles lvalues, rvlaues, const and non-const. The
item&&
is a forwarding reference, it does perfect forwarding. The auto means automatic type deduction. One can't put const before the auto, put the whole thing in a function, send h as a const reference argument.
1 2 3 4 5 6
|
// choose a better name than h
for (auto item&& : h) { //item is one of the members of the container h
if ( item.second.getname() == name ) {
// do something
}
}
|
A different version, not as good as the first one:
1 2 3 4 5 6
|
// choose a better name than h
for (const auto item& : h) { item is passed by const reference.
if ( item.second.getname() == name ) {
// do something
}
}
|
Good Luck!!