【问题标题】:iterator creation in my own class c++11 [duplicate]在我自己的 C++11 类中创建迭代器 [重复]
【发布时间】:2013-08-19 21:12:18
【问题描述】:

我是 c++ 编程的新手,我需要创建迭代器,但我遇到了循环问题(在 c++11 中),因为它无法识别元素,我解释一下:

class myclass{
    std::string str;
    myclass();
    std::iterator<(what do i have to put here?), char, diffptr_t, char*, char&> begin(){
       return str.begin();
    }
}

这是读取类的方法:

 void func(myclass& m){
     for(char a: m){ //Here's the problem, i don't know why it doesn't work
         //do function  
     }

任何人都可以说出哪种方法是最好的方法吗?还有什么问题???

【问题讨论】:

  • 就像一个注释,std::iterator 是为了帮助实现迭代器而不是实际用作迭代器的类型。

标签: loops c++11 iterator


【解决方案1】:

至少如果我正确理解你的问题,你想要这样的东西:

class myclass { 
    std::string str;
public:
    std::string::iterator begin() { return str.begin(); }
    std::string::iterator end() { return str.end(); }
};

void func(myclass &m) { 
    for (auto a : m)
        // ...
}

【讨论】:

  • 是的,我曾想过,但是,这是为了学习,迭代器是如何创建的? (对不起这里的问题)
  • @user2688108:迭代器是一个重载比较的类,operator*、operator++,可能还有更多(例如,operator--,如果它是双向迭代器)。 Here's 一个例子。
  • 迭代器也应该继承自std::iterator 或者自己提供一堆嵌套的typedefs
【解决方案2】:

如果您只是从 std::string 返回迭代器,那么您应该能够执行以下操作:

auto begin() -> decltype(str.begin())
{
    return str.begin();
}

一个简单的迭代器确实可以非常简单。它需要能够与另一个自己类型的迭代器进行比较,并且它至少需要前缀增量运算符(基于范围的 for 循环才能工作),当然还有取消引用操作。就是这样。

在你的情况下,它可能是这样的

class iterator
{
    friend myclass;  // So that only `myclass` can construct this

public:
    bool operator==(const iterator& other) const
    {
        // Implement comparison
    }

    iterator& operator++()
    {
        // Increment
        return *this;
    }

    char& operator*() const
    {
        // Return a reference to the "current" character
    }

    friend bool operator!=(const iterator& i1, const iterator& i2)
    {
        return !(i1 == i2);
    }

private:
    iterator(...) { ... }

    // Put the actual iterator here (e.g. `std::string::iterator`)
};

【讨论】:

  • 目前我将使用这些方法(cmets 1 和 2),但我需要知道如何创建迭代器。谢谢大家
  • @user2688108 查看我的更新答案
  • 您应该使用适当的 value_type 从 std::iterator 继承或自己提供这些嵌套类型,以便将此迭代器与标准算法一起使用。
  • @TemplateRex 没有必要从std::iterator 继承,因为该类并没有真正实现任何东西,甚至没有要覆盖的接口,它只是有一些有用的类型别名。
  • 类型别名是满足迭代器要求所必需的。您如何将没有这些嵌套类型的迭代器传递给标准算法?
猜你喜欢
  • 2010-09-13
  • 1970-01-01
  • 2014-08-08
  • 1970-01-01
  • 2010-12-16
  • 2013-08-09
  • 1970-01-01
  • 2011-02-09
  • 2015-02-12
相关资源
最近更新 更多