簡體   English   中英

將指針轉換為STL中的反向矢量迭代器

[英]convert a pointer to a reverse vector iterator in STL

我有

sort(arr, arr+n, pred);

如何以相反的順序排序?

似乎也有可能使用反向迭代器...除了使用反向謂詞可能更容易,除非在類型未實現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));

您可以在標准庫中使用greater的庫,該庫會自動為您要排序的類型調用operator>

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

取反pred的返回值。

正如alrady所說,您應該提供一個反向謂詞。 如果由於某些原因(例如純粹的懶惰)而無法進行操作,則始終可以先排序然后反轉:

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

這對於計算機來說將是更多的工作,但是很明顯並且可以完成工作。 如果您需要這種速度性能,請使用反向謂詞解決方案。

我似乎很容易

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/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM