std::out of range...

When i run this program.
It gives me this error:
1
2
terminate called after throwing an instance of 'std::out of range'
   what<>: vector::_M_range_check

Why it gives this error?
How to fix it?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
  #include <iostream>

#include <fstream>
#include <vector>
using namespace std;
int a,b,set;
vector<int> mat;

vector< vector<char> > litera;

//function that transforms
void transform(int q,int w){
for (int x=0;x<a;x++){
	for (int y=0;y<b;y++){
	if (litera.at(q).at(w)==litera.at(x).at(y))
	litera.at(q).at(w)=litera.at(0).at(0);
	
	}
}	
	
}
//function that verifies
int verific(int p,int c)
{
   if (litera.at(p).at(c)==litera.at(0).at(0))
   return 1;
   else return 0;	
} 

void back(int nr,int i,int j)
{
	if ((verific(i-1,j)==0)&&(i>0)){
	i--;
	set=litera.at(i).at(j);
	transform(i,j);
	nr++;
		back(nr,i,j);

		
}

if ((verific(i,j+1)==0)&&(b-1>j)){
	j++;
	set=litera.at(i).at(j);
	nr++;
	transform(i,j);
		back(nr,i,j);
		
}

if ((verific(i+1,j)==0)&&(a-1>i)){
	i++;
	set=litera.at(i).at(j);
	nr++;
	transform(i,j);
		back(nr,i,j);
			
}

if ((verific(i,j--)==0)&&(j>0)){
	j--;
	set=litera.at(i).at(j);
	nr++;
	transform(i,j);
		back(nr,i,j);
		
}	
  mat.push_back(nr);
	litera.at(i).at(j)=set;	
}


int main(){
	cin>>a;
	cin>>b;
	litera.resize(a);

for(int m=0;m<=a;m++)
{
	
	litera[m].resize(b);
}
	for (int x=0;x<a;x++){
	for (int y=0;y<b;y++){
	cin>>litera.at(x).at(y);
	
	}
}	
int manr=0;
back(0,0,0);
for (int pi=0;pi<mat.size();pi++)
{
	if (mat.at(pi)>manr)
mat.at(pi)=manr;
}

cout<<manr;

	return 0;
}

Thanks in advance.
Last edited on
line 78, shouldnt that be < instead of <= in your for loop.
line 89 you have a uninitialised variable here, and your testing against it on line 93.

There may be other errors.
It's definitely <=.
I changed manr=0.
But it still gives the error.


Lastly, you call back(0,0,0) on line 90, from within the back function you subtract 1 giving -1 resulting in a out of range error.
It doesnt substract since i put i>0.
I just debug stepped it and it did.
ok...
i will try to change the program a little

when int verific(int p, int c) is called, c = 0 and p = -1 resulting in a out of range.


Remember that if ((verific(i - 1, j) == 0) && (i>0)){ will call verific passing whatever is in i minus 1 when it does the IF statement check.
Last edited on
Thanks
Softrix is correct. Line 78 should be <, not <=.

Lets assume that a = 10. Line 76, you resize the outer vector to 10 elements. Those elements are [0]-[9]. As coded, the for loop at line 78 will execute 11 times. On the last iteration, m=10, which is out of bounds when referencing litera[10].
Last edited on
Topic archived. No new replies allowed.