首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用std::sort对C++中的数组进行排序

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

Stack Overflow用户
提问于 2011-05-05 20:01:08
回答 12查看 201.8K关注 0票数 93

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

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

EN

回答 12

Stack Overflow用户

回答已采纳

发布于 2011-05-05 20:04:26

在C++0x/11中,我们得到了数组重载的std::beginstd::end

代码语言:javascript
运行
复制
#include <algorithm>

int main(){
  int v[2000];
  std::sort(std::begin(v), std::end(v));
}

如果您无法访问C++0x,那么自己编写它们并不困难:

代码语言:javascript
运行
复制
// 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;
}
票数 113
EN

Stack Overflow用户

发布于 2011-05-05 20:02:24

代码语言:javascript
运行
复制
#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

代码语言:javascript
运行
复制
#include <algorithm>
#include <array>
std::array<int, 2000> v;
// Fill the array by values
std::sort(v.begin(),v.end()); 
票数 75
EN

Stack Overflow用户

发布于 2011-05-05 20:04:18

如果你不知道大小,你可以使用:

代码语言:javascript
运行
复制
std::sort(v, v + sizeof v / sizeof v[0]);

即使你知道数组的大小,用这种方式编码也是个好主意,因为如果以后改变数组的大小,这将减少出现bug的可能性。

票数 34
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5897319

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档