This is a code that I wrote for a Topcoder SRM. However there is a segmentation fault here that I cannot figure out. Can you help me figure it out?
The problem is -
This task is about the scoring in the first phase of the die-game Yahtzee, where five dice are used. The score is determined by the values on the upward die faces after a roll. The player gets to choose a value, and all dice that show the chosen value are considered active. The score is simply the sum of values on active dice. Say, for instance, that a player ends up with the die faces showing 2, 2, 3, 5 and 4. Choosing the value two makes the dice showing 2 active and yields a score of 2 + 2 = 4, while choosing 5 makes the one die showing 5 active, yielding a score of 5. Your method will take as input a vector toss, where each element represents the upward face of a die, and return the maximum possible score with these values.
Constraints -
toss will contain five elements exactly. Each element will be between 1 and 6
#include <iostream>
#include <vector>
using namespace std;
class YahtzeeScore
{
public:
int maxPoints(vector<int> toss);
};
int YahtzeeScore::maxPoints(vector <int> toss)
{
vector<int> ret;
vector <int>::iterator v = toss.begin();
vector<int>::iterator w = toss.begin();
for (;v != toss.end(); v++)
{
int s=0;
for (;w != toss.end(); w++)
{
if ( w!=v && *w==*v) s++;
}
ret.push_back(s);
}
vector<int>::iterator it = ret.begin();
for (; it!=ret.end(); it++)
{
if (*v>*(v+1))
{
int temp = *v;
*v = *(v+1);
*(v+1)=temp;
}
}
return ret[4];
}
int main()
{
YahtzeeScore ob;
vector<int> something;
vector<int>::iterator it = something.begin();
while (it != something.end())
{
int a;
cin >> a;
something.push_back(a);
}
cout << ob.YahtzeeScore::maxPoints(something);
}
w = toss.begin();in everyfor (;v != toss.end(); v++)so thewiteration works properly only for the forstvloop.main(), you are doingpush_backinto the vector you are iterating through. That invalidates the iterator. (Also, what is the point of the iterator there? There vector starts empty.)