How to use std::sort to sort an array in C++(如何使用 std::sort 在 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::begin
和 std::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;
}
这篇关于如何使用 std::sort 在 C++ 中对数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 std::sort 在 C++ 中对数组进行排序


- 将函数的返回值分配给引用 C++? 2022-01-01
- XML Schema 到 C++ 类 2022-01-01
- 使用 __stdcall & 调用 DLLVS2013 中的 GetProcAddress() 2021-01-01
- GDB 不显示函数名 2022-01-01
- 从父 CMakeLists.txt 覆盖 CMake 中的默认选项(...)值 2021-01-01
- 将 hdc 内容复制到位图 2022-09-04
- 如何提取 __VA_ARGS__? 2022-01-01
- OpenGL 对象的 RAII 包装器 2021-01-01
- DoEvents 等效于 C++? 2021-01-01
- 哪个更快:if (bool) 或 if(int)? 2022-01-01