lRinzu
lRinzu

Reputation: 21

How to search in `std::list` of struct?

The problem is that I can not search in a std::list, according to the user-input vID.

I have tried many different approaches but it did not work.

struct VideoDetails
{
  int VidID, Copies;
  string MovieTitle, Genre, Production, FileName;

};
list <VideoDetails> MyList;
int vID;
cin >> vID;

First attempt:

find_if(MyList.begin(), MyList.end(), [](VideoDetails & VD) {return VD.VidID == vID; });

Second attempt:

auto pred = [](const VideoDetails & ID) { return ID.VidID == vID;  };
find_if(Mylist.begin(), MyList.end(), vID) != MyList.end();

Third attempt:

list <VideoDetails>::iterator iter;
for(iter = MyList.begin(); iter != MyList.end(); ++iter)
{
  if ((*iter).VidID == vID) {
    //  
  } else {
    //
  }
}

First attempt error:

Error (active) E1738 the enclosing-function 'this' cannot be referenced in a lambda body unless it is in the capture list mp 3      

Third attempt error:

Error C2678 binary '==': no operator found which takes a left-hand operand of type 'int' (or there is no acceptable conversion) mp 3

Upvotes: 2

Views: 732

Answers (1)

JeJo
JeJo

Reputation: 32722

First method: You did not capture the vID inside the lambda, that's what the error message complaining about.

const auto iter = std::find_if(MyList.begin(), MyList.end(), 
                  [vID](const VideoDetails& VD) {return VD.VidID == vID; });
         //        ^^^^

And do not forget to get the iterator returning from std::find_if, in case of further use. If you correct the above, your first method will work.

Second method: Has no big difference than the one. The lambda has the same problem as the above. In addition to that std::find_if required an unary predicate, not a value to be found in the container. Change to

auto pred = [vID](const VideoDetails & ID) {   return ID.VidID == vID; }
//           ^^^^
if(std::find_if(Mylist.begin(), MyList.end(), pred ) != MyList.end())
//                                            ^^^^
{
   // do something
}

If you have made work with the std::find_if and lambda, you do not need to go for the third attempt.

Upvotes: 4

Related Questions