Boost::filesystem, std::sort: trouble retaining information on sort passes

前端 未结 1 1998
伪装坚强ぢ
伪装坚强ぢ 2021-01-23 05:07

I\'m trying to use std::sort on a data type that contains information read from a boost::filesystem::dictionary_iterator. It appears that as the sortin

1条回答
  •  伪装坚强ぢ
    2021-01-23 05:33

    The call to compare() at the end is wrong, it returns an int that can be -1, 0 or 1 like strcmp(). Use a simple call to std::less()(a_filename, b_filename) instead. Also make sure you have unit tests that make sure the comparator creates a strict-weak ordering, as is required for std::sort.

    Comparator with internal checking:

    inline bool do_compare(const File& a, const File& b)
    {
        /* ... */
    } 
    
    bool compare(const File& a, const File& b)
    {
        bool const res = do_compare(a, b);
        if(res)
            assert(!do_compare(b, a));
        return res;
    }
    

    If NDEBUG is defined (i.e. assert() deactivated) the compiler should be able to optimize this to the same amount of code as before. And now, I wish you much fun writing the code that sorts the filenames 9.png, 10.png and 11.png in that order. ;)

    0 讨论(0)
提交回复
热议问题