c++ implementing iterators for custom matrix class

前端 未结 1 1138
余生分开走
余生分开走 2021-01-26 03:55

I am currently working on a linear algebra library (custom vector and matrix plus some algorithms) for educational purposes and personal use. I tried to implement a column itera

相关标签:
1条回答
  • 2021-01-26 04:54

    I found a solution to the problem. It's a combination of:

    this: Get each nth element of iterator range and this: http://www.codeproject.com/Questions/331444/How-to-use-boost-filter-iterator-as-a-class-member

    In the end, there was no way around boost. The solution is very simple and looks like:

     template<class U>
     struct EveryNth {
         bool operator()(const U& ) { return m_count++ % N == 0; }
         EveryNth(std::size_t i) : m_count(0), N(i) {}
     private:
         int m_count;
         std::size_t N;
     };
    
    class Matrix{
    // code here
    
        typedef boost::filter_iterator<EveryNth<T>, 
                                   typename std::vector<T>::iterator> FilterIter;
    
        FilterIter  begin_jump(std::size_t i){
            return boost::make_filter_iterator<EveryNth<T> >(EveryNth<T>(i), data.begin(),      data.end());
        }
    
        FilterIter end_jump(std::size_t i){
           return boost::make_filter_iterator<EveryNth<T> >(EveryNth<T>(i), data.end(), data.end());
        }
    

    };

    and the main:

    int main(int argc, char *argv[]){
    
        std::vector<int> b = {1,2,3,4,5,6,7,8,9};
        MVector<int> a = MVector<int>(b);
        for_each(a.begin_jump(2), a.end_jump(2), 
                 [](int i){std::cout << i << " " ;} 
            );
    
        std::cout << std::endl;
        return 0;
    }
    
    bash-3.2$ ./main
    1 3 5 7 9 
    

    or using a.begin_jump(3) instead of two:

    bash-3.2$ ./main
    1 4 7 
    

    which is exactly the intended result.

    0 讨论(0)
提交回复
热议问题