是否可以为现有的POD类型元素数组创建类似STL的容器,甚至只是STL样式的迭代器?
例如,假设我有一个int数组.能够直接在此数组上调用某些STL函数(例如find_if,count_if或sort)会很方便.
非解决方案:复制整个数组,甚至只是引用元素.目标是节省内存和时间,同时希望允许使用其他STL算法.
您可以直接在常规C样式数组上调用许多STL算法 - 它们是为此而设计的.例如,:
int ary[100]; // init ... std::sort(ary, ary+100); // sorts the array std::find(ary, ary+100, pred); find some element
我想你会发现大多数东西都像你期望的那样有效.
所有STL算法都使用迭代器.
指针是对象数组中的有效迭代器.
NB结束迭代器必须是超出数组末尾的一个元素.因此,以下代码中的数据+ 5.
#include#include #include int main() { int data[] = {4,3,7,5,8}; std::sort(data,data+5); std::copy(data,data+5,std::ostream_iterator (std::cout,"\t")); }
您可以使用内联函数模板,这样就不必复制数组索引
templateinline T * array_begin (T (&t)[I]) { return t; } template inline T * array_end (T (&t)[I]) { return t + I; } void foo () { int array[100]; std::find (array_begin (array) , array_end (array) , 10); }