Search code examples
sortingcontainersoption-typestdoptional

How to sort container with std::optional type?


Looking for a way to sort an optional container Like the following...

#include <optional>
#include <vector>

using optional = std::optional<int>;
std::vector<optional> cont;

int main()
{
   auto min_iter = std::min_element(cont.begin(), cont.end());
   std::sort(cont.begin(), cont.end());
}

Solution

  • to get a guaranteed max/min element that passes has_value()

    using optional = std::optional<int>;
    std::vector<optional> cont = {2, 1, 4, {}, 7};
    
    std::sort(cont.begin(), cont.end());
    
    // Find first which passes has_value(), as sorted this should be minimum.
    auto min_iter = std::find_if(cont.cbegin(), cont.cend(), 
         [](const auto& element) { 
             return element.has_value(); 
         }
     );
    // Find last which passes has_value(), as sorted this should be maximum.
    auto max_iter = std::find_if(cont.crbegin(), cont.crend(), 
        [](const auto& element) { 
            return element.has_value(); 
        }
    );
    auto min_value = min_iter->value();
    auto max_value = max_iter->value();
    

    I am a simple man who likes simple solutions, so yes it can go through the container up to 2x.