本文介紹了如何使用 std::sort 在 C++ 中對數組進行排序的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
如何使用標準模板庫 std::sort()
對聲明為的數組進行排序int v[2000]
;
How to use standard template library std::sort()
to sort an array declared as
int v[2000]
;
C++ 是否提供了一些函數可以獲取數組的開始和結束索引?
Does C++ provide some function that can get the begin and end index of an array?
推薦答案
在 C++0x/11 中,我們得到 std::begin
和 std::end
為數組重載:
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;
}
這篇關于如何使用 std::sort 在 C++ 中對數組進行排序的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!