迭代器无缘无故地迭代 c++
所以我试图实现一个插入函数,它将一个元素插入列表中的正确顺序。
我的输入为:
b.insert('Z');
b.insert('J');
b.insert('Y');
并且应该输出为:
JY Z
我首先将迭代器指向列表的开头,然后迭代每个对象,直到找到正确的位置来输入它。我不明白为什么,但是当我开始迭代时,它在进入循环后向前跳一位。
class list < node<T>* >::iterator itr = bt->level().begin();
cout << "itr now: " << (*itr)->getItem() << endl;
while (itr != bt->level().end()) {
cout << "itr now: " << (*itr)->getItem() << " and " << elem << endl;
// do a bunch of other stuff
++itr;
}
我的输出应该是这样的:
itr now: Z
itr now: Z and J
itr now: J
itr now: J and Y
但相反,
itr now: Z
itr now: Z and J
itr now: J
itr now: Z and Y
有人可以告诉我发生了什么导致这个问题吗?
So I am trying to implement an insert function, which inserts an element into the correct order on the list.
my input goes as:
b.insert('Z');
b.insert('J');
b.insert('Y');
and should output as:
J Y Z
I start off by making my iterator point at the beginning of the list and then iterate through each object until I find the correct spot to enter it in. I don't understand why, but when I start off with the iteration, it jumps ahead one spot after it enters the loop.
class list < node<T>* >::iterator itr = bt->level().begin();
cout << "itr now: " << (*itr)->getItem() << endl;
while (itr != bt->level().end()) {
cout << "itr now: " << (*itr)->getItem() << " and " << elem << endl;
// do a bunch of other stuff
++itr;
}
my output for this should look like:
itr now: Z
itr now: Z and J
itr now: J
itr now: J and Y
but instead it comes out as
itr now: Z
itr now: Z and J
itr now: J
itr now: Z and Y
can somone tell me whats happening thats causing this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
请在此处发布完整的代码,如果您正在寻找排序顺序,则只需将元素插入到容器中并使用标准的算法排序即可为您解决问题。
Please post your complete code here, if you are looking for sorted order then just insert the element in
container
and use standardalgorithm sort
that would do the trick for you.