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

新手上路,请多包涵

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

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

原文由 user707549 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 403
2 个回答

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

原文由 Xeo 发布,翻译遵循 CC BY-SA 3.0 许可协议

sort() 可以应用于 C++ 中的数组和向量来对元素进行排序或重新排列。

1. C++ sort() 在向量的情况下:

// 导入向量、算法和 iostream

使用命名空间标准;

int main() {

向量 v = {5,4,3,2,8}; // 取决于你的向量大小

排序(v.begin(),v.end());

cout<[1]; //通过打印测试排序的元素位置

返回0;

}

2. C++ sort() 在数组的情况下:

// 包括算法和 iostream

使用命名空间标准;

int main() {

整数数组[] = {10, 35, 85}; // 数组大小 2000 int n = sizeof(array)/sizeof(array[0]);

排序(数组,数组+3);

cout<<数组[0];

返回0;

}

注意:上述两个片段在发布之前都使用现代 C++ 版本(11,17 和 20)进行了测试。

原文由 Farial Mahmod 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题