当前位置:  开发笔记 > 编程语言 > 正文

现有阵列周围的STL非复制包装?

如何解决《现有阵列周围的STL非复制包装?》经验,为你挑选了3个好方法。

是否可以为现有的POD类型元素数组创建类似STL的容器,甚至只是STL样式的迭代器?

例如,假设我有一个int数组.能够直接在此数组上调用某些STL函数(例如find_if,count_if或sort)会很方便.

非解决方案:复制整个数组,甚至只是引用元素.目标是节省内存和时间,同时希望允许使用其他STL算法.



1> 1800 INFORMA..:

您可以直接在常规C样式数组上调用许多STL算法 - 它们是为此而设计的.例如,:

int ary[100];
// init ...

std::sort(ary, ary+100); // sorts the array
std::find(ary, ary+100, pred); find some element

我想你会发现大多数东西都像你期望的那样有效.



2> Martin York..:

所有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"));
}



3> Richard Cord..:

您可以使用内联函数模板,这样就不必复制数组索引

template 
inline 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);
}

推荐阅读
惬听风吟jyy_802
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有