【问题标题】:STL list iterator outside of rangeSTL 列表迭代器超出范围
【发布时间】:2018-01-07 20:22:31
【问题描述】:

我不知道为什么我的代码中会出现这个错误。(实际上,这是我第一次使用 std::list。)当我使用它时 ++ 它会产生错误“列表迭代器超出范围”,当我使用 ++it 它会使错误“列表迭代器不可递增”。请帮帮我!

#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);
}

【问题讨论】:

  • 这个row[y].erase(it++); 是未定义的行为。
  • std::list::erase 返回的迭代器是出于您似乎需要的原因而提供的。也许it = row[y].erase(it);
  • 顾名思义,迭代器用于迭代。将它们用作指针通常只会导致悲伤。
  • erase() 函数从容器中删除预期的元素,并返回一个指向下一个有效元素(如果有)的迭代器。因此,从迭代器中删除元素时,无需在擦除后递增迭代器,因为擦除的返回值将是指向有效元素的迭代器(如果有)。如果没有元素存在,它将返回 Container.end()。
  • 行[y].remove_if(*it);试过 row[y].insert(temp.pos, temp.data);

标签: c++ list stl containers


【解决方案1】:

要在迭代时从 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() );
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-11-22
  • 1970-01-01
  • 1970-01-01
  • 2014-01-16
  • 2018-01-30
  • 1970-01-01
  • 2021-01-23
相关资源
最近更新 更多