#include<iostream>
#include<vector>
#include<sstream>
#include<algorithm>
#include<cmath>
#include<string>
using namespace std;

class ComboLength
{
	public:
	int howLong(string moves)
	{
		vector<int> cc;
		int i,j,k=0;
		for(i=0;i<moves.size()-1;++i)
		{
			if(moves[i]==moves[i+1])       //Error
			k++;
			else
			cc.push_back(k);
		}
		return *max_element(cc.begin(),cc.end());
	}
};

I get a segementaion error in line if (moves==moves[i+1])
any idea why?

Recommended Answers

All 2 Replies

Why calling the function moves.size() again and again for every loop ??? Do it once,else its just a waste of computation time.

Do this :

int max=moves.size()-1;
for(i=0;i<max;++i)
{
	if(moves[i]==moves[i+1])       
		k++;
	else
		cc.push_back(k);
}

And with respect to the segmentation fault I am not finding any problem with the code.Well may be its not because of the statement you said.

start quote:

#include<iostream>
#include<vector>
#include<sstream>
#include<algorithm>
#include<cmath>
#include<string>
using namespace std;

class ComboLength
{
    public:
    int howLong(string moves)
    {
        vector<int> cc;
        int i,j,k=0;
        for(i=0;i<moves.size()-1;++i)
        {
            if(moves[i]==moves[i+1])       //Error
            k++;
            else
            cc.push_back(k);
        }
        return *max_element(cc.begin(),cc.end());
    }
};

I get a segementaion error in line if (moves[i]==moves[i+1])
any idea why?

i can see the problem here..

return *max_element(cc.begin(),cc.end());

it shouldn't be like that, what if no values are being inserted in the vector. and your test [icode] moves[i] == moves[i+1] succeeded all the time then vector "cc" will be empty and max_elements return the last iterator which is not an element. and dereferencing an unknown element is segmentation fault.. (in complete description but sufficient at this level).

so change this code to following.

vector<int>::iterator maxIter = max_element(cc.begin(),cc.end());
if (maxIter != cc.end()){ 
     return *maxIter;               // not a good way either. but will work.
} 
else {
     return -1;                       // logically indicatting no value depends on implementation.
}

Hope this helps

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.