Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterator for a custom unbound array

I implemented my own small UnboundArray class:

template <typename T>
class UnboundArray {
private:
    std::vector<T> elementData;
public:
    ...
    std::size_t size()
    {
        return elementData.size();
    }
};

And I have a class in which I want to use my UnboundArray, especially I need to use a for loop on UnboundArray elements:

for (auto const &row : unbound_arrays) {
// loop over unbound array of unbound arrays and call its size method or something else
}

I'm really new to C++ iterators and do not know what path I should follow. Should I implement from scratch my iterator or should I make a member in my UnboundArray which is of type std::iterator?

like image 332
Jacobian Avatar asked Dec 31 '25 10:12

Jacobian


1 Answers

If you mostly need to use a range based for loop with your custom class UnboundArray, you might start with implementing begin() and end() methods for UnboundArray:

auto begin() { return std::begin(elementData); }
auto end() { return std::end(elementData); }

so the loop works:

UnboundArray<int> unbound_array;

for (auto const &elem: unbound_array) { // ... }

wandbox example


It is important to note that you need const overloads in order to iterate through a const UnboundArray:

auto begin() const { return std::cbegin(elementData); }
auto end() const { return std::cend(elementData); }
like image 104
Edgar Rokjān Avatar answered Jan 03 '26 22:01

Edgar Rokjān



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!