简体   繁体   中英

convert a pointer to a reverse vector iterator in STL

I have

sort(arr, arr+n, pred);

How do I sort in reverse order?

There also seems to be a possibility to use reverse iterators ... except using the reversed predicate might be easier, except perhaps when the type doesn't implement operator> :)

#include <iostream>
#include <algorithm>
#include <iterator>

int main()
{
    int arr[4] = { 3, 2, 5, 4 };
    std::sort(std::reverse_iterator<int*>(arr + 4), std::reverse_iterator<int*>(arr));
}

如果您获得了pred (即您无法进入它来颠倒顺序),则类似:

std::sort(arr, arr+n, boost:bind<bool>(pred, _2, _1));

You could use greater from the standard library which calls operator> automatically for the type you want to sort.

#include <funcitonal>
.....
sort(arr, arr+n, greater<Type>()); // Type could be double for example

取反pred的返回值。

As alrady said, you should provde a reversed predicate. If you can't for some reasons (like pure laziness), you can always first sort then reverse :

sort(arr, arr+n, pred);
reverse( arr, arr+n );

That would be more work for the computer but it's clear and does the job. If you need speed performance for this sort, use the reversed predicate solution.

Quite Easy i seems

std::sort(myVec.rbegin(),myVec.rend());


int main() 
{
    typedef std::vector<int> vecType;
    vecType myVec;
    for(int a=0;a<20;a++)
    {
        myVec.push_back((rand()%100));
    }
    std::copy(myVec.begin(), myVec.end(), std::ostream_iterator<int>(std::cout, "\n"));
    cout<<"\n---------------------------------------------------\n";
    std::sort(myVec.rbegin(),myVec.rend());
    std::copy(myVec.begin(), myVec.end(), std::ostream_iterator<int>(std::cout, "\n"));
    return 0;   
}
sort(arr, arr+n, std::not1(pred));

请参阅: http//www.cplusplus.com/reference/std/functional/not1/

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