list iterator not decrementable

江尹城 2015-10-25 11:14:17
再用STL List写Josephus环问题的时候遇到了list iterator not decrementable,网上看了一些解答也完成不了,求大神来解答一下,感激不尽!!

#include<iostream>
#include<list>
using std::list;
using namespace std;

int InitJCircle(int n,int k){
list<int> ilist;
for (int i = n; i >= 1; i--){
ilist.push_front(i);
}//Init

int order[100];
list<int>::iterator it = --( ilist.begin());

while (!ilist.empty()){
int i = 0;
for (int j = 1; j <= k; j++){
if (++it == ilist.end())
it=ilist.begin(); }
order[i] = *it;
ilist.erase(it);
i++;
}//GetOrder

int i = 0;
while (order[i]){
cout << order[i] << " ";
i++;
}
return 0;
}

int main(){
int n, k;
cout << "Please input the n and k:" << endl << "n = ";
cin >> n;
cout << endl << "k = ";
cin >> k;
cout << "The order is :";
InitJCircle(n,k);
}
...全文
176 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
ri_aje 2015-10-26
  • 打赏
  • 举报
回复
引用 2 楼 z49434574 的回复:
[quote=引用 1 楼 ri_aje 的回复:] --( ilist.begin()); 会导致未定义行为的,begin 返回的迭代器不能 --。
改成了it = ilist.begin(); it --; 还是不可以[/quote] 所以我后面还加了一句,"begin 返回的迭代器不能 --",你在二楼试的方法恰恰就是这句涵盖的未定义行为。
江尹城 2015-10-25
  • 打赏
  • 举报
回复
引用 1 楼 ri_aje 的回复:
--( ilist.begin()); 会导致未定义行为的,begin 返回的迭代器不能 --。
改成了it = ilist.begin(); it --; 还是不可以
ri_aje 2015-10-25
  • 打赏
  • 举报
回复
--( ilist.begin()); 会导致未定义行为的,begin 返回的迭代器不能 --。

3,881

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 其它技术问题
社区管理员
  • 其它技术问题社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧