本文介紹了如何使用 std::sort 在 C++ 中對(duì)數(shù)組進(jìn)行排序的處理方法,對(duì)大家解決問題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
如何使用標(biāo)準(zhǔn)模板庫 std::sort()
對(duì)聲明為的數(shù)組進(jìn)行排序int v[2000]
;
How to use standard template library std::sort()
to sort an array declared as
int v[2000]
;
C++ 是否提供了一些函數(shù)可以獲取數(shù)組的開始和結(jié)束索引?
Does C++ provide some function that can get the begin and end index of an array?
推薦答案
在 C++0x/11 中,我們得到 std::begin
和 std::end
為數(shù)組重載:
In C++0x/11 we get std::begin
and std::end
which are overloaded for arrays:
#include <algorithm>
int main(){
int v[2000];
std::sort(std::begin(v), std::end(v));
}
如果您無法訪問 C++0x,那么自己編寫它們并不難:
If you don't have access to C++0x, it isn't hard to write them yourself:
// for container with nested typedefs, non-const version
template<class Cont>
typename Cont::iterator begin(Cont& c){
return c.begin();
}
template<class Cont>
typename Cont::iterator end(Cont& c){
return c.end();
}
// const version
template<class Cont>
typename Cont::const_iterator begin(Cont const& c){
return c.begin();
}
template<class Cont>
typename Cont::const_iterator end(Cont const& c){
return c.end();
}
// overloads for C style arrays
template<class T, std::size_t N>
T* begin(T (&arr)[N]){
return &arr[0];
}
template<class T, std::size_t N>
T* end(T (&arr)[N]){
return arr + N;
}
這篇關(guān)于如何使用 std::sort 在 C++ 中對(duì)數(shù)組進(jìn)行排序的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請(qǐng)聯(lián)系我們刪除處理,感謝您的支持!