-2

I am trying to use an iterator find() to retrieve the pointer to a node class that contains a certain value.

Is there a better way than doing something like this?

typedef vector<Node*> Vmap; 
Vmap vmap;

for(Vmap::iterator itr = vmap.begin(); itr != vmap.end(); itr++) {
    if((*itr)->getVal() == 3) {
         // do something
    }
}

Desired:

Vmap::iterator itr = find(vmap.begin(), vmap.end, 3) // return Node pointer with value == 3

Node* temp_node = *itr

Thank you

EDIT: Additional information to supplement given answer.

What is a lambda expression in C++11?

Community
  • 1
  • 1
jsmiao
  • 433
  • 1
  • 5
  • 13

2 Answers2

2
Vmap::iterator itr = std::find_if(vmap.begin(), vmap.end(),
  [](Node* node) { return node->getVal() == 3; } );
Igor Tandetnik
  • 50,461
  • 4
  • 56
  • 85
1

You may use std::find_if:

auto itr = std::find_if(vmap.begin(),
                        vmap.end(),
                        [](const Node* node) { return node->getVal() == 3;});
Jarod42
  • 203,559
  • 14
  • 181
  • 302