我不知道为什么在我的代码中发生了这个错误。(实际上,这是我第一次使用std :: list。)当我使用它时,它会使错误'列表迭代器超出范围',当我使用++它会使错误'list iterator not incrementable'。请帮帮我!
#include<stdio.h>
#include<stdlib.h>
#include<list>
#include<stack>
using namespace std;
typedef struct tag_vpos { int data; list <int>::iterator pos; } vpos;
list<int> row[100];
stack<vpos> save[100];
int col[100][100], n, r, rowsize[100];
//int row[100][100];
long long cnt;
void arr(int x, int y) {
list<int>::iterator it = row[y].begin();
while (it != row[y].end()) {
if (!col[x][*it]) {
vpos t = { *it, it }, temp;
int val = *it;
col[x][val] = 1;
row[y].erase(it++);
save[y].push(t);
if (x == r - 1) { // if x th column is the end of right
if (y == r - 1) cnt++; // if y th column is the bottom, count this
else arr(0, y + 1);// else fill next row, first column
}
else { arr(x + 1, y); } // else fill next right square
temp = save[y].top();
row[y].insert(temp.pos, temp.data);
save[y].pop();
col[x][temp.data] = 0;
}
else it++;
}
return;
}
void main() {
printf("Input n, r (paint r x r field with n colors, same color cannot be used in same column and row) \n: ");
scanf("%d %d", &n, &r);
for (int i = 0; i < r; i++) {
for (int j = 0; j < n; j++) row[i].push_back(j);
rowsize[i] = n;
}
printf("start\n");
arr(0, 0);
printf("There are %ld ways to paint.\n", cnt);
}
答案 0 :(得分:0)
要在迭代时从STL容器中删除元素,请将容器的erase函数(它们都具有此功能)与remove or remove_if算法组合在一起。否则你的自己下面的迭代器就会失效。
void delete_elements(std::list &list)
{
list.erase(
std::remove_if(
list.begin(),
list.end(),
[](char x){return std::isspace(x);}),
list.end() );
}