2

I've got a vector with objects of a custom data type. One of the fields of this data type is an enum. I want to make sure that for all enum values at least one entry is added to the vector.

I want to use std::find_if() to check if the vector has an entry for a certain enum value. But I'm not sure how to write & use the lambda correctly. Here's what I got:

struct CustomType { EnumType type {EnumType::DEFAULT}; int x; }; std::vector<CustomType> tmp; // fetch values from database and add them to the vector // for some EnumType values there might not be a record added to the vector auto hasEnumType = [](const CustomType& customType, const EnumType& enumType) -> bool { return (customType.type == enumType); }; // What do I replace '?' with to get the current position if (std::find_if(tmp.begin(), tmp.end(), hasEnumType(?, EnumType::VALUE1)) != tmp.end()) { //add CustomType with VALUE1 to vector } 

2 Answers 2

3

If you want to check against a fixed value, you can simply put it inside the lambda.

if ( std::find_if(tmp.begin(), tmp.end(), [](CustomType const & customType) { return customType.type == EnumType::VALUE; }) ) { /* do something */} 

If you want, in a sense, pass it to lambda as parameter, you can set it in an external variable and "capture" it by reference

auto enumType = EnumType::VALUE; // capture variables by references --------V if ( std::find_if(tmp.begin(), tmp.end(), [&](CustomType const & customType) { return customType.type == enumType; }) ) { /* do something */ } 
Sign up to request clarification or add additional context in comments.

Comments

0

std::find_if takes a unary predicate as its third parameter. If you provide binary predicate it will fail type check.

One way to do this is to convert your binary predicate to unary predicate by capturing one of its parameters. To automate it for all enum values create a function that returns another function.

auto getTypeChecker = [](const EnumType enumType) { return [enumType](const CustomType& customType) { return (customType.type == enumType); }; }; 

then declare a function that takes care of inserting enum values that are not present in the vector -

void insert_if_not_present(std::vector<CustomType>& vec, const EnumType type) { if(std::none_of(begin(vec), end(vec), getTypeChecker(type))) { //add CustomType with type to vec } } 

Now call insert_if_not_present once for each enum value.

Note, here I have used std::none_of for convenience. You can use std::find_if in place of std::none_of in smae manner.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.