strings. what was I doing wrong?

so I know this isn't the best way to find a max sequence in a string but it was a work in progress and an idea, problem is I couldn't even get it to run.

I kept getting Debug assertion failure string subscript out of range, I played with all sorts of stuff but with no luck. I replaced the appends and clears with assigns and all sorts of stuff but just never got it to run with "Debug assertion failure string subscript out of range" :(.

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
void sequence (string str1)
{
	string largestsequence;
	string nextsequence;
	largestsequence.append(str1, 0, 1);	
	int j = 0;
	for (int i = 1; i < str1.length(); i++)
	{
		if (str1[i] > largestsequence[j])
		{
			largestsequence.append(str1, i, 1);
			j ++;
		}
	}
	for (int i = 1; i < str1.length(); i++)
	{
		int j = i;
		nextsequence.append(str1, i, 1);
		for (int k = i + 1; k < str1.length(); k++)
		{
			if (str1[k] > nextsequence[j])
			{
				nextsequence.append(str1, k, 1);
				j++;
			}
		}
		if (largestsequence.length() > nextsequence.length())
			nextsequence.clear();
		else
		{
			largestsequence.assign(nextsequence);
			nextsequence.clear();
		}
	}
	cout << largestsequence;

}
on line 17 you set j so that j == i

You never check to make sure j is less than nextsequence.length()

You then use j to index nextsequence on line 21.

Since you are clearing nextsequence on lines 28 and 32, it's almost certain that j will be greater than nextsequence's length. Hence why you're getting the out of bounds message.


Also, why are you starting at 1 everywhere? Indexes start at 0.
Topic archived. No new replies allowed.