简体   繁体   中英

c++ creating an const iterator for a costum class

I am having a custom template class -

template <class T>
class myClass{
    vector<vector<T>> matrix;
    //rest of the code...
};

I want to be able to have a const iterator begin to myClass and const iterator end to myClass that would able to iterate over the objects T in the matrix of myClass, I'm struggling to create such thing.

in my mind, I want to gather all objects T at the matrix to some local one-dimensional vector and return the iterator.begin to this vector or iterator.end to this vector

furthermore, I want to be able to support for-each loop as follows:

for(const auto& obj : instaceOfMyClass)

Thanks!

in my mind, I want to gather all objects T at the matrix to some local one-dimensional vector and return the iterator.begin to this vector

That would imply copying the whole matrix. A big no-no. Not only because of the time of the copying, the effective doubling of space, but also because you would have elements duplicated in two locations. When one it's modified the other retains the old value.

You have two options:

Flatten the matrix storage

template <class T>
class myClass{
    vector<T> matrix;

    T& get(size_t line, size_t column)
    {
         return matrix[line * columns_count + column];
    }
};

This is good for two reasons: better cache locality and easy to implement iterators:

using ConstIterator = std::vector<T>::const_iterator;

ConstIterator cbegin() const { return matrix.cbegin(); }

Implement the iterator

If you want to keep the 2dim storage then you need to implement the iterator. It's a little too much boilerplate for my taste, so I will give you just a guidance to get you started if you wish to go this route:

The iterator should keep an pointer/reference to the matrix, a pointer/reference/index to the current line and one to the current column. On ++ operation go next on the column and if you reached the end of the column then increase the line and reset the column.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM