首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为c++标准容器实现自定义迭代器

为c++标准容器实现自定义迭代器
EN

Stack Overflow用户
提问于 2014-10-17 20:12:35
回答 1查看 3K关注 0票数 1

我正在尝试为我的Vector/Matrix类编写一个自定义迭代器。迭代器的目的是遍历std::vector并跳过每第n个元素。我已经问了一个类似的问题c++ implementing iterators for custom matrix class,它确实提供了一个问题的解决方案。

然而,这种方法太慢了。我做了相当多的阅读:有效的C++,C++入门等和在线资源:http://www.drdobbs.com/stl-generic-programming-writing-your-ow/184401417How to correctly implement custom iterators and const_iterators?,当然还有:http://www.cplusplus.com/reference/iterator/iterator/

最后一个特别提供了一个有效的代码。但是,我不能真正弄清楚代码的作用以及如何为std::vector实现这一点。代码如下:

代码语言:javascript
复制
template<class T>
class iter: public std::iterator<std::random_access_iterator_tag, T>{
private:
    T* m_pter;

public:

    iter(T* value):  m_pter(value){}
    iter(const iter& other_it): m_pter(other_it.m_pter){}
    iter& operator++() { ++m_pter; return *this; }
    bool operator!=(const iter& rhs) {return m_pter!=rhs.m_pter;}
    T& operator*() { return *m_pter; }

};

主要的是:

代码语言:javascript
复制
int main(int argc, char *argv[]){

    int a[]  = {1,2,3,4,5,6};
    iter<int> from(a);
    iter<int> to(a+5);
    for (iter<int> iter = from; iter != to; ++iter) {
        std::cout << *iter << std::endl;
    }

    // std::vector<int> a  = {1,2,3,4,5,6};
    // iter<std::vector<int> > from(a);
    // iter<std::vector<int> > to(a+5);
    // for (iter<std::vectorVECTOR<int> > iter=from; iter!=to; ++iter) {
    //     std::cout << *iter << std::endl;
    // }

}

main函数的上半部分返回:$ ./main 1 2 3 4 5

下半部分:

代码语言:javascript
复制
main.cpp:49:21: error: no matching function for call to ‘iter<int>::iter(std::vector<int>&)’
     iter<int> from(a);

我真的很想知道为什么代码只适用于数组,而不适用于向量。为了让它对向量起作用,我需要做哪些更改?

非常感谢您的意见。

文森

EN

回答 1

Stack Overflow用户

发布于 2014-10-17 20:29:52

这实际上很简单,this article提供了帮助。

代码语言:javascript
复制
int main {
    std::vector<int> a  = {1,2,3,4,5,6};
    iter<int> from(&a[0]);
    iter<int> to(&a[5]);
    for (iter<int> iter = from; iter < to; ) {
        std::cout << *iter << std::endl;
    }
}

这对于进一步的规范来说已经足够好了。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26424784

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档