简体   繁体   中英

Pass a vector as a range to std::sort - C++17

I wrote this code in order to simplify the use of std::for_each when I need to go through an entire collection:

namespace ranges {
    template<typename Range, typename Function>
    Function for_each(Range &range, Function f) {
        return std::for_each(std::begin(range), std::end(range), f);
    }
}

So that I can use it like this:

ranges::for_each(a, foo);

This had worked for me and since I also have to sort entire collections, I thought it would be a good idea to implement the same process with std::sort , just like this:

namespace ranges {
    template<typename Range, typename Function>
    Function for_each(Range &range, Function f) {
        return std::for_each(std::begin(range), std::end(range), f);
    }

    template<typename Range, typename Function>
    Function sort(Range &range, Function f) {
        return std::sort(std::begin(range), std::end(range), f);
    }
}

When I add that code to my namespace, the compiler throws me the following error message:

error: void value not ignored as it ought to be

Is there a way to achieve what I want to do? I'm using the C++17 standard and g++.exe (Rev1, Built by MSYS2 project) 11.2.0 to compile.

Your implementation of for_each works, because the definition of std::for_each you're using is defined as follows:

namespace std {
    template <class Iterator, class Function>
    Function for_each(Iterator begin, Iterator end, Function f);
};

However , std::sort as invoked is defined as follows:

namespace std {
    template <class Iterator, class Function>
    void sort(Iterator first, Iterator last, Function comp);
};

In your definition of sort , you cannot return the result of the call to std::sort , because the return types for the two functions are distinct.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM