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

84 c++ sorting

如何使用标准模板库std::sort()对声明为的数组进行排序 int v[2000];

C++是否提供了一些可以获取数组的开始和结束索引的函数?

Xeo*_*Xeo 102

在C++ 0x中/ 11,我们得到std::beginstd::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)

  • 是`std :: begin()`和`std :: end()`C++ 1x的补充?它们非常好 - 应该从一开始就是这样,它会使很多算法更通用! (12认同)
  • `std :: begin()`和`std :: end()`不是当前C++标准的一部分,但你可以使用`boost :: begin()`和`boost :: end()`. (10认同)
  • 提醒一下:早在他们提出C++ 11之前,我们大多数人都在我们的个人工具包中有这样的`begin`和`end`功能.然而,在C++ 11之前,它们有一个严重的缺点:它们没有导致整数常量表达式.因此,根据具体需求,我们会使用它们,或者使用两个`sizeof`进行划分的宏. (2认同)

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)

  • +1:正确但非常脆弱.如果排序不在声明附近,则在维护期间很容易破坏. (4认同)
  • 当然,使用文字数组大小总是很危险的,如示例中所示.但是将数组大小放入'const int'没有任何问题. (2认同)

j_r*_*ker 31

如果您不知道尺寸,可以使用:

std::sort(v, v + sizeof v / sizeof v[0]);
Run Code Online (Sandbox Code Playgroud)

即使您确实知道大小,最好以这种方式对其进行编码,因为如果稍后更改数组大小,它将减少错误的可能性.

  • 由于您正在编写将来的证明代码,而不是使用`sizeof x/sizeof*x`技巧,您应该使用更安全的模板:`template <typename T,int N> int array_size(T(&)[N]){return N; },因为如果不是数组而传递指针,那将失败.如果需要,它可以转换为编译时常量,但在注释中读取有点太难了. (7认同)
  • 如果它是静态分配的,他应该知道大小,因为编译器知道.但这是更好的编码实践. (3认同)

May*_*ank 17

你可以对它进行排序 std::sort(v, v + 2000)

  • +1:正确但非常脆弱.如果排序不在声明附近,则在维护期间很容易破坏. (4认同)