如何使用标准模板库std::sort()对声明为的数组进行排序
int v[2000];
C++是否提供了一些可以获取数组的开始和结束索引的函数?
Xeo*_*Xeo 102
在C++ 0x中/ 11,我们得到std::begin和std::end它们重载数组:
#include <algorithm>
int main(){
int v[2000];
std::sort(std::begin(v), std::end(v));
}
Run Code Online (Sandbox Code Playgroud)
如果您无法访问C++ 0x,则自己编写它们并不困难:
// 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;
}
Run Code Online (Sandbox Code Playgroud)
Nas*_*zta 65
#include <algorithm>
static const size_t v_size = 2000;
int v[v_size];
// Fill the array by values
std::sort(v,v+v_size);
Run Code Online (Sandbox Code Playgroud)
在C++ 11中:
#include <algorithm>
#include <array>
std::array<int, 2000> v;
// Fill the array by values
std::sort(v.begin(),v.end());
Run Code Online (Sandbox Code Playgroud)
j_r*_*ker 31
如果您不知道尺寸,可以使用:
std::sort(v, v + sizeof v / sizeof v[0]);
Run Code Online (Sandbox Code Playgroud)
即使您确实知道大小,最好以这种方式对其进行编码,因为如果稍后更改数组大小,它将减少错误的可能性.
| 归档时间: |
|
| 查看次数: |
176900 次 |
| 最近记录: |