这是在实现一个迭代器std::list<std::vector<char>>
第一次尝试:自定义迭代器不取消引用问题
Document.h
#ifndef Document_h
#define Document_h
//-------------------------------------------------------------------------
typedef std::vector<char> Line; // line of text
//-------------------------------------------------------------------------
class Text_iterator
{
public:
Text_iterator(std::list<Line>::iterator l, Line::iterator p)// constructor
: ln(l), pos(p) { }
Text_iterator(const Text_iterator& src) // copy constructor
: ln(src.ln), pos(src.pos) { }
Text_iterator& operator= (const Text_iterator& src) // copy assignment
{
Text_iterator temp(src);
this->swap(temp);
return *this;
}
char& operator*() { return *pos; } // dereferencing
Text_iterator& operator++() // incrementation
{
++pos;
if (pos == ln->end())
{
++ln;
pos = ln->begin();
}
return *this;
}
bool operator== (const Text_iterator& other) const // comparison
{
return ln == other.ln && pos == other.pos;
}
bool operator != (const Text_iterator& other) const // comparison
{
return !(*this == other);
}
void swap(Text_iterator& src) // helper: swap
{
std::swap(src.get_line(), ln);
std::swap(src.get_column(), pos);
}
std::list<Line>::iterator get_line() { return ln; } // accessors
Line::iterator get_column() { return pos; }
private:
std::list<Line>::iterator ln; // data members
Line::iterator pos;
};
//-------------------------------------------------------------------------
void swap (Text_iterator& lhs, Text_iterator& rhs) // object swap
{
lhs.swap(rhs);
}
//-------------------------------------------------------------------------
class Document
{
public:
typedef Text_iterator iterator;
public:
Document() // constructor
{
Line l(10, 'a');
text.push_back(l);
}
iterator begin() // iterator to first element
{
return iterator(text.begin(), (*text.begin()).begin());
}
iterator end() // iterator to last element
{
return iterator(text.end(), (*text.end()).end());
}
void print()
{
for (Document::iterator p = begin(); p != end(); ++p)
{
std::cout << *p;
getchar();
}
}
std::list<Line> text; // data member
};
#endif
main.cpp
#include <iostream>
#include <sstream>
#include <vector>
#include <list>
#include <algorithm>
#include "Document.h"
int main()
{
Document text;
text.print();
}
预期输出:
AAAAAAAAAA
代替上述期望输出的获取:
调试断言失败
表达:列表迭代器不dereferencable。
为什么我得到这种行为以及如何纠正?
注:短暂的研究之后,我发现,最常见的原因为这样的行为是在提领该end()
迭代器的尝试,但我无法找到我的代码这样的表达。
您的迭代器需要存储每个容器的结尾以及开始。 –