Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda function with map where key is tuple and value is double

I have a map, filled with values:

std::map<std::tuple<int, int, double>, double> Cache;

When the size of map is greater than 100, I want to delete/erase only the map elements whose values in the key tuple are all more than 10. Here is how it can be done with while and if:

if (Cache.size() > 100) {
    auto it = Cache.begin();
    while (it != Cache.end()) {
        auto myCache = it->first;
        auto actualX = std::get<0>(myCache);
        auto actualY = std::get<1>(myCache);
        auto actualZ = std::get<2>(myCache);
        if (abs(actualX) > 10 || abs(actualY) > 10) || abs(actualZ) > 10)) {
            Cache.erase(it++);
        } else {
            it++;
        }
    }
}

How one can implement the same behavior using find_if (or other function) and lambda function?

Update2

After going through the wikipedia link provided in the comment section i have implemented the following code, but its giving an compiler error :(

Cache.erase(std::remove_if(Cache.begin(),
                                 Cache.end(),
                                 [=](auto &T) -> bool {
                                     auto myCache = T->first;
                                     auto actualX = std::get<0>(myCache);
                                     auto actualY = std::get<1>(myCache);
                                     return std::abs(actualX) > 10|| std::abs(actualY) > 10 || std::abs(actualZ) > 10;
                                 }),
                  Cache.end());

update 3

The above cannot be used with map ;(


1 Answers

You can use std::find_if with predicate:

auto pred = []( const auto &t ) { 
    return std::abs( std::get<0>( t. ) ) > 10 || 
           std::abs( std::get<1>( t ) ) > 10 || 
           std::fabs( std::get<2>( t ) ) > 10.0 ); };

for( auto it = Cache.begin(); true; it = Cache.erase( it ) ) {
     it = std::find_if( it, Cache.end(), pred );
     if( it == Cache.end() ) break;
}
like image 179
Slava Avatar answered Feb 20 '26 16:02

Slava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!