如何使用标准模板库std::sort()
对声明为int v[2000]
的数组进行排序;
C++是否提供了一些可以获取数组的开始和结束索引的函数?
发布于 2011-05-05 20:04:26
在C++0x/11中,我们得到了数组重载的std::begin
和std::end
:
#include <algorithm>
int main(){
int v[2000];
std::sort(std::begin(v), std::end(v));
}
如果您无法访问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;
}
发布于 2011-05-05 20:02:24
#include <algorithm>
static const size_t v_size = 2000;
int v[v_size];
// Fill the array by values
std::sort(v,v+v_size);
在C++11中
#include <algorithm>
#include <array>
std::array<int, 2000> v;
// Fill the array by values
std::sort(v.begin(),v.end());
发布于 2011-05-05 20:04:18
如果你不知道大小,你可以使用:
std::sort(v, v + sizeof v / sizeof v[0]);
即使你知道数组的大小,用这种方式编码也是个好主意,因为如果以后改变数组的大小,这将减少出现bug的可能性。
https://stackoverflow.com/questions/5897319
复制相似问题