180*_*ION 22
您可以直接在常规C样式数组上调用许多STL算法 - 它们是为此而设计的.例如,:
int ary[100];
// init ...
std::sort(ary, ary+100); // sorts the array
std::find(ary, ary+100, pred); find some element
Run Code Online (Sandbox Code Playgroud)
我想你会发现大多数东西都像你期望的那样有效.
所有STL算法都使用迭代器.
指针是对象数组中的有效迭代器.
NB结束迭代器必须是超出数组末尾的一个元素.因此,以下代码中的数据+ 5.
#include <algorithm>
#include <iostream>
#include <iterator>
int main()
{
int data[] = {4,3,7,5,8};
std::sort(data,data+5);
std::copy(data,data+5,std::ostream_iterator<int>(std::cout,"\t"));
}
Run Code Online (Sandbox Code Playgroud)
您可以使用内联函数模板,这样就不必复制数组索引
template <typename T, int I>
inline T * array_begin (T (&t)[I])
{
return t;
}
template <typename T, int I>
inline T * array_end (T (&t)[I])
{
return t + I;
}
void foo ()
{
int array[100];
std::find (array_begin (array)
, array_end (array)
, 10);
}
Run Code Online (Sandbox Code Playgroud)