0

I am trying to find if a string words contains any instruction form machine_opTable, a vector of pair-string,int.

What should my lambda function look like in find_if ? If you have any other approach, please let me know.

As of now, my code looks like ...

# define RX 4
# define RR 2

...

vector < pair <string, int> > machine_opTable = { {"L", RX},
                                                  { "A", RX},
                                                  {"ST", RX}
                                                };

words = " L 1, SMB1";

string inMachineop;
for ( auto instruction: words){

    inMachineop = find_if ( begin(machine_opTable), end(machine_opTable), [] (const pair<string,int>& p) { return  ( p.first == instruction ? p.first : "NOTFOUND"); });

}

I would love to return iterator pointing to that pair... Please show me how it's done.

Thank you.

Mumbaikar007
  • 441
  • 1
  • 6
  • 16
  • [`find_if`](http://en.cppreference.com/w/cpp/algorithm/find) takes a predicate – a truth-valued function – and returns an iterator. – molbdnilo Feb 01 '18 at 07:07

2 Answers2

3

Return value from find_if according to reference is

An iterator to the first element in the range for which pred does not return false.

pred is your lambda and it must return bool value. If you want to use instruction in your lambda, you have to capture this variable

[instruction] (const pair<string,int>& p) { return  p.first == instruction; }

and the call of find_if when we know it returns iterator looks as follows

auto it = find_if ( begin(machine_opTable), end(machine_opTable), [instruction] (const pair<string,int>& p) { return  p.first == instruction; });
if (it != machine_opTable.end())
{
    // access to found pair
}
else 
    ; // pair not found
rafix07
  • 20,001
  • 3
  • 20
  • 33
1

I see a bug here:

for ( auto instruction: words){

You iterate by characters, not by words here. You need to split by space first. Try to use this code for that task https://stackoverflow.com/a/27511119/9187525

Bugs related to find_if() was explained by others :)

Eugene Kosov
  • 993
  • 7
  • 15