了解运算符重载和迭代器,为什么它会打印出"wrhrwwr"?
Understanding operator overloading & iterator why does it print out "wrhrwwr"?
在下面的代码中,输出是"wrhrwwr",我试图理解迭代器在做什么,以及"++"是如何重载的。似乎它以某种方式跳过了"e"。但是,代码对我来说很不清楚,也许我可以得到帮助。 谢谢
#include <iostream>
using namespace std;
class datas {
private:
const char *string,marker;
const int len;
public:
class hophop {
private:
const char *pos, next;
public:
char operator *() { return *pos; }
hophop operator ++() {++pos;while (*(pos+1)!=next) ++pos; return *this; }
bool operator !=(hophop &o) { return pos < o.pos; }
hophop(const char *p, char m) : pos(p),next(m) {}
};
typedef hophop iterator;
iterator begin() { return hophop (string, marker); }
itrator end () { return hophop(string +len ,marker); }
datas(const char *d,int l, char m) : string (d), len(l),marker(m){}
};
int main( void ) {
datas chars ("we are where we were", 20, 'e');
for (char c: chars)
cout << c;
return 0;
}
将hophop
从datas
类中拉出会更容易看到。现在,您可以看到hophop
构造函数及其用途。我会删除++operator
的返回值,将其设置为 void,以指出它在这里没有任何作用。
#include <iostream>
class hophop {
private:
const char* pos, next;
public:
hophop(const char* p, char m) : pos(p), next(m) {}
char operator *() { return *pos; }
hophop operator ++() {
++pos;
while (*(pos + 1) != next)
++pos;
return *this;
}
bool operator !=(const hophop& o) { return pos < o.pos; }
};
class datas {
private:
using iterator = hophop;
const char* string, marker;
const int len;
public:
datas(const char* d, int l, char m) : string(d), len(l), marker(m) {}
iterator begin() { return hophop(string, marker); }
iterator end() { return hophop(string + len, marker); }
};
int main(void) {
datas chars("we are where we were", 20, 'e');
// w r h r w w r
for (char c : chars)
std::cout << c;
std::cout << "nusing a non range based for loop:" << std::endl;
for (hophop it = chars.begin(); it != chars.end(); ++it)
std::cout << *it;
std::cout << "nor where the return value could be used:" << std::endl;
auto it = chars.begin();
std::cout << *it;
for (; it != chars.end();)
std::cout << *++it;
}
所以现在可能更容易看到 hophop ++ 运算符是如何工作的。operator *()
在循环开始时被调用,因此无论第一个字符是什么,它都会被检索。然后调用++operator
,它将迭代器至少向前移动一次,直到它与next
匹配。然后它返回匹配前的字符。主要查看评论。返回e
之前的第一个和每个字符。
如果您没有经常使用调试器,您应该这样做。 通过在operator++
中放置断点,您可以看到正在发生的事情。
更新
我之前已将++operator
的返回值设置为 void。正如@JaMiT指出的那样,操作员返回*this
是合适的。我还添加了另外两个循环,它们应该比使用基于范围的循环更清晰。第三个例子实际上使用了++operator
的返回值,前两个循环没有。
而且,养成不using namespace std;
的习惯 这将使您免于未来的麻烦。
相关文章:
- 如何循环打印顶点结构
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 如何在c++中打印目录
- 有一个打印语句的函数是一种糟糕的编程实践吗
- 在线编译器中的分段C++没有打印消息
- 在C++中打印指向不同基元数据类型的指针的内存地址
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值
- 如何将结构插入到集合中并打印集合的成员
- 在循环C++中指定字符串之后,不会打印该字符串
- 以螺旋方式打印矩阵的程序.(工作不好)
- 从控制台中删除最后打印的元素
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 如何仅使用对象名称打印特定于对象的成员
- 回溯C++不打印函数,因此文件
- 在一定长度后从数组中打印时缺少整数
- 为什么这个 c++ 代码打印出长度 5,当我打印出字符串时,程序会自动终止?
- 在gem5中打印文件中的所有cache_blocks
- 打印数字图案
- Log4cpp:以UTC/GMT时区打印日期
- 了解运算符重载和迭代器,为什么它会打印出"wrhrwwr"?