代码之家  ›  专栏  ›  技术社区  ›  Tyler

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

  •  9
  • Tyler  · 技术社区  · 17 年前

    例如,假设我有一个int数组。可以方便地调用一些STL函数,例如find_if、count_if或直接在此数组上排序。

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

    5 回复  |  直到 17 年前
        1
  •  22
  •   1800 INFORMATION    17 年前

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

    int ary[100];
    // init ...
    
    std::sort(ary, ary+100); // sorts the array
    std::find(ary, ary+100, pred); find some element
    

        2
  •  5
  •   Richard Corden    17 年前

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

    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);
    }
    
        3
  •  5
  •   Loki Astari    17 年前

    所有STL算法都使用迭代器。
    指针是对象数组的有效迭代器。

    请注意

    #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"));
    }
    
        4
  •  4
  •   Ferruccio    13 年前

    你可以用 Boost.Array

    使用数组:

    int a[100];
    for (int i = 0; i < 100; ++i)
        a[i] = 0;
    

    使用boost.Array:

    boost::array<int,100> a;
    for (boost::array<int,100>::iterator i = a.begin(); i != a.end(); ++i)
        *i = 0;
    

    更新: 使用C++11,您现在可以使用 std::array

        5
  •  2
  •   Matt Price    17 年前

    指针是迭代器的有效模型:

    struct Bob
    { int val; };
    
    bool operator<(const Bob& lhs, const Bob& rhs)
    { return lhs.val < rhs.val; }
    
    // let's do a reverse sort
    bool pred(const Bob& lhs, const Bob& rhs)
    { return lhs.val > rhs.val; }
    
    bool isBobNumberTwo(const Bob& bob) { return bob.val == 2; }
    
    int main()
    {
        Bob bobs[4]; // ok, so we have 4 bobs!
        const size_t size = sizeof(bobs)/sizeof(Bob);
        bobs[0].val = 1; bobs[1].val = 4; bobs[2].val = 2; bobs[3].val = 3;
    
        // sort using std::less<Bob> wich uses operator <
        std::sort(bobs, bobs + size);
        std::cout << bobs[0].val << std::endl;
        std::cout << bobs[1].val << std::endl;
        std::cout << bobs[2].val << std::endl;
        std::cout << bobs[3].val << std::endl;
    
        // sort using pred
        std::sort(bobs, bobs + size, pred);
        std::cout << bobs[0].val << std::endl;
        std::cout << bobs[1].val << std::endl;
        std::cout << bobs[2].val << std::endl;
        std::cout << bobs[3].val << std::endl;
    
        //Let's find Bob number 2
        Bob* bob = std::find_if(bobs, bobs + size, isBobNumberTwo);
        if (bob->val == 2)
            std::cout << "Ok, found the right one!\n";
        else 
            std::cout << "Whoops!\n";
    
        return 0;
    }