Baz
Baz

Reputation: 13175

Iterate over boost::shared_array

How would you iterate over the items in a boost::shared_array? Would you do a get() on it and use a raw pointer as the iterator?

Upvotes: 3

Views: 4300

Answers (2)

jrok
jrok

Reputation: 55425

Since you're already using boost, maybe like this:

#include <boost/shared_array.hpp>
#include <boost/range.hpp>
#include <iostream>

int main()
{
    boost::shared_array<int> arr(new int[10]());

    int* ptr = arr.get();
    for (int i : boost::make_iterator_range(ptr, ptr+10))
    {
        std::cout << i << ',';
    }
}

In any case, you need to do your own bookeeping of array's size.

Upvotes: 3

Tony The Lion
Tony The Lion

Reputation: 63310

Seeing you'd already know the size of the array by the fact it had to be allocated before you create the boost::shared_array, the only way I see to iterate it is to use a normal for loop and then use operator[i] on the boost::shared_array to get an element.

Upvotes: 2

Related Questions