如何使用std :: sort在C ++中排序数组 [英] How to use std::sort to sort an array in C++
本文介绍了如何使用std :: sort在C ++中排序数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用标准模板库 std :: sort()
来排序声明为
int v [2000] / code>;
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, t难以自己写:
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 ++中排序数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文