如何使用 std::sort 在 C++ 中对数组进行排序

2021-12-10 00:00:00 sorting 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::beginstd::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;
}

相关文章