Search code examples
c++arraysstliterator

STL non-copying wrapper around an existing array?


Is it possible to create an STL-like container, or even just an STL-style iterator, for an existing array of POD-type elements?

For example, suppose I have an array of ints. It would be convenient to be able to call some of the STL functions, such as find_if, count_if, or sort directly on this array.

Non-solution: copying the entire array, or even just references to the elements. The goal is to be very memory- and time-saving while hopefully allowing use of other STL algorithms.


Solution

  • You can call many of the STL algorithms directly on a regular C style array - they were designed for this to work. e.g.,:

    int ary[100] = ...;
    // init ...
        
    // note: technically, std::begin(ary) can just be ary in this context
    std::sort(std::begin(ary), std::end(ary));        // sort the array
    std::find(std::begin(ary), std::end(ary), pred);  // find some element
    
    // or since C++20:
    std::rangs::sort(ary);
    std::ranges::find(ary, pred);
    

    I think you'll find that most stuff works just as you would expect.